简体   繁体   中英

Appending information to seperate divs when they all have the same class name

I have a bunch of divs with the same class name. I loop through some information placing each into a div. I want to append them into separate divs but the fact that they all have the same name is hindering me from this process. Instead of appending it to the current modal it appends all the information to all divs with that class name. How can I get around this ?

You can use JQuery's "each" loop.

$(".className").each(function(e){
    $(this).html("new content"); // $(this) will give you the reference of your current element.
});

You can loop as Gaurav said. This will work nicely if you know the data will match the order of the divs. If you want to place items in specific locations (AKA the data is not coming out in the same order as the divs), and if jQuery is an option (you didn't secify), you can use jQuery's eq() selector . Doing this, you can make a selection like (from jQuery's API docs) this which selects the third td:

<table border="1">
  <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
  <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
  <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>

<script>
$( "td:eq( 2 )" ).css( "color", "red" );
</script>

With that said, if you're able to, and it makes sense to, I would recommend to distinctly identify your divs. Writing JavaScript which matches some piece of data to a particular element in the DOM based on positioning is prone to error - particularly if someone follows you to work on the code and doesn't know about this possible "magic."

$outer = document.getElementsByClassName('outer');

for(var i = 0; i < $outer.length; i++) {
    $outer[i].onclick = function () {
        alert();
    }
}

This will do the trick. You need to loop through all class and apply action respectively.

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