简体   繁体   中英

Get nearest <p> tag text using JavaScript

Here are the p tags that auto populate on page load with multiple options.

<div  id="bunchOfChoices" class="choices">
            {% for user in users %}
            <p id="searchOpts" class="searchOpts">{{user.username}}</p>
            {% endfor %}</div>


<script>
var opts = document.getElementById('searchOpts');
opts.onclick = function(event) {
var target = event.target || event.srcElement;

the_user = target.innerHTML;
href= "/../users/"+String(the_user);
window.location=href;

};
</script>

This code seems to only get the first "searchOpt". Also, I am aware I can use <a> tags instead of this method.

ID should be unique for one element. If you need to categorize multiple p with same name, you can use class and then use below one:

document.getElementsByClassName("searchOpts");

Demo:

 console.log(document.getElementsByClassName('searchOpts')[1]); 
 <p id="searchOpts1" class="searchOpts">Name 1</p> <p id="searchOpts2" class="searchOpts">Name 2</p> 

A few things here:

Misuse of id

You should never have multiple elements on the page with the same id . You should use class and leave the id out.

Assigning onclick handlers:

You can use the classes to assign onclick handlers as follows:

<script>
    for (let opt of Array.from(document.getElementsByClassName("searchOpts"))) {
        opt.onclick = () => {
            window.location.href = "/../users/" + opt.textContent;
        }
    };
</script>

HTML pages should only ever have one element marked with any particular id . Here you are marking all <p> elements with the id searchOpts . This is incorrect.

You would be better to remove the id and just use the class . Then search for all elements with that class:

var allSearchOpts = document.querySelectorAll(".searchOpts");

This returns an element list, so you need to loop over the list to set the click handler on each element.

allSearchOpts.forEach( function(el) {
     el.onclick = ...
} );

You are using document.getElementById this gets the first item with this id. when you use IDs the ID name must be unique.

If you need to add the event for multi-elements use queryselectorall and add your event for every item.

Check this answer

Try using jQuery, you can get the next p by using

$(this).next("p");

in your onclick function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM