Repeat id of the div [duplicate] - javascript

This question already has answers here:
Get "id" and add in each div (name = "id")
(3 answers)
Closed 7 years ago.
I'm still learning, so I'm racking my brain.
$('.post-outer .post-footer .post-footer-line.post-footer-line-2 .post-labels a').each(function(index, el) {
$('.post-outer').attr('itemtype', $(this).attr('href') );
});
When you run the JS above it only takes the first "href" repeating in other "DIV". What is going on:
<div class="post-outer" id="001" itemtype="url1">test1</div>
<div class="post-outer" id="002" itemtype="url1">test2</div>
<div class="post-outer" id="003" itemtype="url1">test3</div>
I wanted to happen this:
<div class="post-outer" id="001" itemtype="url1">test1</div>
<div class="post-outer" id="002" itemtype="url2">test2</div>
<div class="post-outer" id="003" itemtype="url3">test3</div>
Here in the example it just takes the last div and repeated in other
https://jsfiddle.net/mpb9wfmc/

Using .each you can use this for the current element be iterated though:
$(this).attr('itemtype', newValueHere );
Doing $('.post-outer').attr('itemtype', $(this).attr('href') ); will apply it to all items with the class post-outer.

Related

jQuery: Remove string that has no parent element [duplicate]

This question already has answers here:
Remove text with jQuery
(4 answers)
How do I remove text from a node?
(2 answers)
Closed 11 months ago.
I have a document that I can't edit in PHP looking like this:
<div class="car-search-field-div">
<label class="simple_hide">Türen</label>
<div class="myClear"></div>
doors_count
<input id="car-search-form-field-doors_count" name="search[doors_count]" type="text" value="" placeholder="Anzahl Türen ab">
</div>
Now I am trying to remove the string "doors_count" via jQuery but can't adress it properly. When I try something like:
$('.car-search-field-div').remove('iventory_number', '');
The placeholder of the input field gets removed, but the string "doors_number" still is there. I also thought of using the xpath of the string, but that doesn't work either.
Is there a way to adress / remove a string that has no element wrapped around it? Thank you very much in advance!
you can remove inside all text inside .car-search-field-div
$('.car-search-field-div').contents().filter(function () {
return this.nodeType === 3;
}).remove();
more detail enter link description here
demo
You need DOM access
document.querySelector(".car-search-field-div").childNodes.forEach(node => {
if (node.nodeType === 3 && node.textContent.trim() === "doors_count") node.remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="car-search-field-div">
<label class="simple_hide">Türen</label>
<div class="myClear"></div>
doors_count
<input id="car-search-form-field-doors_count" name="search[doors_count]" type="text" value="" placeholder="Anzahl Türen ab">
</div>

Get the last occurrence of an element [duplicate]

This question already has answers here:
Get multiple elements by Id
(14 answers)
Closed 5 years ago.
getElementById(id) returns the element with the matching ID attribute. How can I get the last occurrence of this element, as opposed to the first?
<!DOCTYPE html>
<html>
<body>
<button onclick="getLast()">Click me</button>
<div id="username">Lisa</div>
<div id="username">Chris</div>
<script>
function getLast() {
alert(document.getElementById("username").innerHTML);
}
</script>
</body>
</html>
id is always unique. No two DOM elements can have the same id. In your case use the class attribute. Use getElementsByClassName which will return a collection. Get its length and use that value to get the last element.
function getLast() {
var getLastElemIndex = document.getElementsByClassName("username").length - 1;
console.log(getLastElemIndex)
alert(document.getElementsByClassName("username")[getLastElemIndex].innerHTML);
}
<div class="username">Lisa</div>
<div class="username">Chris</div>
<button onclick="getLast()">Click me</button>
id should be unique. But we don't have control on how people write their code and I also meet this case sometimes: "I need to parse the page and they are using same id"
You can treat id as an attribute and use querySelectorAll:
<button onclick="getLast()">Click me</button>
<div id="username">Lisa</div>
<div id="username">Chris</div>
<script>
function getLast() {
tags = document.querySelectorAll('[id="username"]');
alert(tags[tags.length - 1].innerHTML);
}
</script>
And the best practice should be using class.
The id of a HTML element is meant to be unique. You should specify the class instead:
<div class="username">Lisa</div>
<div class="username">Chris</div>
Then use Document.getElementsByClassName() to get all elements of that class:
var usernames = document.getElementsByClassName("username");
Alternatively, you can use Document.querySelectorAll():
var usernames = document.querySelectorAll(".username");
And then you can get the last one:
var lastUsername = usernames[usernames.length - 1];
Even you can do it by tag name div, as #brk said id must be unique.
function getLast(){
var divs = document.querySelectorAll("div");
console.log(divs[divs.length - 1].textContent);
}
getLast();
<button onclick="getLast()">Click me</button>
<div>Lisa</div>
<div>Chris</div>

Why is my clear function not working? [duplicate]

This question already has answers here:
Is "clear" a reserved word in Javascript?
(4 answers)
Closed 6 years ago.
function clear() {
document.getElementById("1").innerHTML = '';
document.getElementById("2").innerHTML = '';
document.getElementById("3").innerHTML = '';
}
<button onclick="clear()">Clear</button>
That is the function and my button that runs it.
The purpose of the function is to clear the paragraphs, but the button does nothing when I tested it out.
Why is this function not running when the button is clicked?
EDIT: sorry if the answer is obvious, i'm a beginner to JS
EDIT: HTML:
<p id="1"></p>
<p id="2"></p>
<p id="3"></p>
There is also a JS function that changes the text of the Paragraphs, but it doesn't loop
Don't name the function clear as the DOM has an old global method named clear. Try something else like clearMe
function clearMe() {
document.getElementById("1").innerHTML = '';
document.getElementById("2").innerHTML = '';
document.getElementById("3").innerHTML = '';
}
<div id="1">
foo
</div>
<div id="2">
foo
</div>
<div id="3">
foo
</div>
<button onclick="clearMe()">Clear</button>

Replace HTML Tag with another HTML [duplicate]

This question already has answers here:
How to add a class to a given element?
(28 answers)
Closed 7 years ago.
I am trying to replace some HTML Tag with another HTML Tag with php or jquery .
My Current Tag (Default) :
<li class="dropdown"> Home</li>
I want to replace above HTML tag with
<li class="dropdown"> Home</li>
Example :
Default tag : <h1> tag </h2>
Replaced tag : <h2> tag </h2>
I already search many articles on stackoverflow but didnt founded solution for it.
Thank in advance
Update
Just saw your question again. You just need to add:
$(".dropdown-toggle").addClass("active");
Example:
Default tag: <h1> tag </h2>
Replaced tag: <h2> tag </h2>
You can use .replaceWith():
$("h1").replaceWith(function() {
return $("<h2 />", {
html: $(this).html()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1> tag </h1>
You just need to add a class active on a, for that just do
$('<li class="dropdown"> Home</li>').find("a").addClass("active")
Try this. I have created a custom function where you can pass the class to be added along with the target element and it would output the entire html back.
$.fn.AddNewClass = function(newClass,targetElement)
{
$(this).contents().filter(function()
{
if($(this).is(targetElement)){
var clone = $(this);
$(clone).addClass(newClass);
$(this).replaceWith($(clone));
}
});
return $(this)[0].outerHTML;
}
var ele = "<li class='dropdown'><a href='index.html' class='dropdown-toggle'>Home</a></li>";
var newEle = $(ele).AddNewClass('active','a.dropdown-toggle');
alert(newEle);
Example : https://jsfiddle.net/DinoMyte/so000t49/5/

How to convert html elements and properties to something else with jquery [duplicate]

This question already has answers here:
how to change an element type using jquery
(11 answers)
Closed 8 years ago.
Nothing major, but I need to know if there is a way for me to change html elements with containing properties to something else with jquery.
What I actually want to do is to change the following piece of markup after a page load:
<div class="stretchMe" data-stretch="#Url.Content("Images/img1.jpg")"></div>
to
<img class="stretchMe" src="#Url.Content("Images/img1.jpg")" />
How to do something like this?
Try with .replaceWith()
html
<div class="stretchMe" data-stretch="#Url.Content(Images/img1.jpg)"></div>
JS
$("div.stretchMe").each(function () {
var class1 = $(this).attr("class");
var src = $(this).data("stretch");
$(this).replaceWith("<img class=" + class1 + " src='" + src + "' />");
});
DEMO
OP
<img class="stretchMe" src="#Url.Content(Images/img1.jpg)">

Categories

Resources