I need to use jQuery to find elements, get their nested paragraph and then add in a div before this paragraph. I have it working fine, but it's very repetitive code and I want to make it more efficient and tidy it up, but I'm not sure how.
Here is the code:
$(".container .row").each(function(index) {
var row1,
row2,
row3,
row4,
newRow1,
newRow2,
newRow3,
newRow4;
row1 = jQuery(this).find(".elementA");
row2 = jQuery(this).find(".elementB");
row3 = jQuery(this).find(".elementC");
row4 = jQuery(this).find(".elementD");
newRow1 = row1.find("p");
newRow2 = row2.find("p");
newRow3 = row3.find("p");
newRow4 = row4.find("p");
$("<div>Test 1</div>").insertBefore(newRow1);
$("<div>Test 1</div>").insertBefore(newRow2);
$("<div>Test 1</div>").insertBefore(newRow3);
$("<div>Test 1</div>").insertBefore(newRow4);
return;
});
div
html string outside of the loop this
context return
at the end is not necessary Code:
var div = "<div>Test 1</div>";
$(".container .row").each(function (index) {
var $this = jQuery(this);
$(div).insertBefore($this.find(".elementA p"));
$(div).insertBefore($this.find(".elementB p"));
$(div).insertBefore($this.find(".elementC p"));
$(div).insertBefore($this.find(".elementD p"));
});
You can also shorten your code as follow if you want to iterate over all the elements whose class starts with element
:
var div = "<div>Test 1</div>";
$(".container .row [class^=element] p").each(function () {
$(div).insertBefore($(this));
});
I'll also suggest you to use the same class name to all the elements instead of elementX
.
Looks like normal selectors can reduce the load.
$(".container .row").each(function (index) {
var newRow = jQuery(this).find(".elementA p, .elementB p, .elementC p, .elementD p");
$("<div>Test 1</div>").insertBefore(newRow);
return;
});
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.