Set it to null and get the variable data in only one line

var checkActiveBrand = $(".brand__title").attr("data-brand-title");

I have this variable to get my data .brand__title, but I also want to check if it was empty or not, but I do not want to use ifto check it.

if(!checkActiveBrand){
 checkActiveBrand = null;
}

I do not want to use this, I want one line to set everything, and if not, return nullwithout using the operator if. Is there any way? because I have a lot of data to check, it will be random if I installed and checked everything one by one.

+4
source share
3 answers

The shortest of them is built-in ||, and you can use the method .data():

var checkActiveBrand = $(".brand__title").data("brandTitle") || null;

console.log(checkActiveBrand);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='brand__title' data-brand-title=''>Data brand title attr is "".</div>
Run codeHide result
+3

checkActiveBrand = (checkActiveBrand) ? checkActiveBrand : null;
0

You can use the ternary operator, which is part of Javascript. You include the condition that you want to check, and then ?followed by a value if true :, a value if false.

var checkActiveBrand = $(".brand__title").attr("data-brand-title") ? $(".brand__title").attr("data-brand-title") : null;
0
source

Source: https://habr.com/ru/post/1666458/


All Articles