dev198742
dev198742

Reputation: 11

jQuery find element with class name which is added dynamically

I have a navigation which is listed dynamically with PHP.

<nav id='navs'>
@foreach($element as $val)
<a data-prop={{$val->id}}>$val->name</a>
@endforeach
</nav>

The html : html The highlighted the tags are listed dynamically

I have a JS script, when we click on the navbar element then we add .selected class to the tag. When the page is loaded the first tag has .selected class.

I need a JS code to find the data-prop attribute value for the elements with .selected class. I tried:

 var d=  $("#navs .selected").attr('data-prop');

but the d variable is undefined. Any suggestion? I also tried the .find() method.

Upvotes: 0

Views: 359

Answers (2)

dev198742
dev198742

Reputation: 11

I figured out what the problem was. I have a script which is adding the class name .selected to the tags, the problem is that it executed AFTER my script, where I wanted to find the element with the .selected class.

So my code is working:

 var d=  $("#navs .selected").attr('data-prop');

Upvotes: 0

Matthias
Matthias

Reputation: 400

For the given example one could to the following:

first get an array of all related elements

 d = $("#navs > a");

And then iterate and get your desired attributes:

for (index = 0; index < d.length; ++index) {
    console.log(d[index].getAttribute("id"));
}

... the given example prints the ID attribute instead your custom attribute (data-prop)

Upvotes: 1

Related Questions