Using a variable value on multiple elements with the same iD - javascript

So I have a file like
<div class="u1">
<p id="level1"></p>
<p id="level2"></p>
</div>
<div class="u2">
<p id="level1"></p>
<p id="level3"></p>
</div>
and if I use something like
document.getElementbyId("level1").innerText(or innerHtml) = "Hello"
it writes that string on one element, and not on every element with id="level1"
I tried with
$('#level1').text("Hello");
but it works only for one.
I need something to write a string on every element with id="level1".

ID is a unique identifier, so you can't have few items with the same ID. Provided HTML code is invalid. You can use CLASS attribute or data-id or....
If you can't change HTML and it comes from third-party dependency, then we have a list of NOT recommended but WORKING solutions
jQuery:
$('[id="level1"]').text("Hello");
js:
var elements = document.querySelectorAll('#level1'); + for loop to iterate elements
And a lot of similar solutions based on knowledges how elements selecting works under the hood

It is ideal to have Unique Ids and thus you cannot update it this way. What you can do is you can give it a class like this:
<div class="u1">
<p id="level1" class="helloText"></p>
<p id="level2"></p>
</div>
<div class="u2">
<p id="level1" class="helloText"></p>
<p id="level3"></p>
</div>
Now use this JS to update the HTML:
var paras = document.getElementsByClassName("helloText");
for (i = 0; i < paras.length; i++) {
paras[i].innerHTML = "Hello";
}
You can also remove the Ids or make them unique to make your code cleaner. It is never recommended to use duplicate Ids.

You give a classname to the elements you need:
class = "levels"
in the script, use document.getElementsByClassName, which return an array with all elements. then you can loop through that array to get the info of each elements.
let levels = document.getElementsByClassName("levels");
for (let j=0; j<levels.length; j++){
levels[j] do something...;
}

Related

Remove randomly generated class and id in with Javascript?

I want to remove the class and id in the website using only Javascript. But that site's class and id contains random numbers and random characters, which looks like this:
<body class="class-abc ahwk-1726-rand_banner-lauwj-5210 other-class">
<div id="fire-id 3762-kahm-rand-banner_9728-jege other-id">
...
The common point of these classes and ids are in the form (some digits or characters)(- or _)banner(- or _)(some numbers or characters).
With CSS, I can easily select them using the CSS Selector: [class*="banner" i] and [id*="banner" i].
However, with the remove() in javascript it does not support CSS Selector.
So, how do I remove classes and ids of this form using Javascript?
Your answer will be highly appreciated!
As you are happy with the CSS selector, just iterate over the matches and delete them. But please note that it is not valid HTML when you have id attributes with spaces in them. An id attribute specifies one identifier, not a space-separated list of them.
So assuming that your HTML would be valid, you can do as follows:
for (let elem of document.querySelectorAll('[id*="banner" i]')) {
elem.removeAttribute("id");
}
for (let elem of document.querySelectorAll('[class*="banner" i]')) {
elem.classList.remove(...elem.className.match(/\S+banner\S+/gi));
}
console.log(document.querySelector("div").outerHTML);
<div class="class-abc ahwk-1726-rand_banner-lauwj-5210 other-class">
<div id="fire-id">
</div>
<div id="3762-kahm-rand-banner_9728-jege">
</div>
<div id="other-id">
</div>
</div>
So for id attributes we may assume that the id attribute can be removed. For class attributes we can search the value for the match(es) using a regular expression, and then pass the matching list to the classList.remove method.
Dealing with invalid HTML
If you really want to change the value of an invalid id property with spaces, then proceed as follows:
for (let elem of document.querySelectorAll('[id*="banner" i]')) {
elem.setAttribute("id", elem.getAttribute("id").replace(/\S+banner\S+/gi, "").replace(" ", " "));
}
for (let elem of document.querySelectorAll('[class*="banner" i]')) {
elem.classList.remove(...elem.className.match(/\S+banner\S+/gi));
}
console.log(document.querySelector("div").outerHTML);
<div class="class-abc ahwk-1726-rand_banner-lauwj-5210 other-class">
<!-- invalid HTML follows... --->
<div id="fire-id 3762-kahm-rand-banner_9728-jege other-id">
</div>
</div>
If you want to remove class or id from specific elements then find elements by tag name and remove class / id attrs like: element.removeAttribute('class') OR element.removeAttribute('id')

How to select element based off specific parent structure in JS?

I am trying to write a script that will get the grab the only if the parent structure is div.main-element input+label+ul.
Is there any appropriate way to set that up using javascript or jquery?
If anyone could direct me to the appropriate answer or documentation that would be absolutely awesome.
My end goal would be to replace the ul>li with an hr tag using either an append or .replace()
here is my HTML:
<div class='main-element'>
<input>
<label></label>
<ul>
<li>Example</li>
</ul>
</div>
<div class='main-element'>
<input>
<label></label>
</div>
You could check if the element that you want exists using this kind of code in jquery :
if($("div.main-element ul li").length){
//your code
}
This will execute on your html example, next you can modify the value of the first element using :
$("div.main-element ul li").append("blahblahblah");
Note that this gives you access to the first li tag found inside of a div.main-element>ul of your html page.
You can provide a second argument to a jquery call that is the parent container within which you want to get elements from. There is also a find function that does the same thing.
HTML:
<div class='main-element'>
<input>
<label></label>
<ul>
<li>Example</li>
</ul>
</div>
<div class='secondary-element'>
<input>
<label></label>
</div>
JS:
var $secondaryElement = $('.secondary-element');
var $secondaryInput = $('input', $secondaryElement);
Another approach:
var $secondaryInput = $('.secondary-element').find('input');
Both of the examples above will return ONLY the input element inside of the secondary-element div.
Does that answer your question?
Links:
https://api.jquery.com/find/
and
https://api.jquery.com/jquery/#selector-context
This will get all elements with your composition and replace ul>li by hr.
var elements = document.querySelectorAll(".main-element input+label+ul li");
for(var i = 0; i < elements.length; i++){
var parent = elements[i].parentNode.parentNode;
var ul = elements[i].parentNode;
ul.parentNode.removeChild(ul);
var hr = document.createElement("hr");
parent.appendChild(hr);
}

How to use getElementByClassName in angularJS to change style properties?

some body please explain me how to get specific class name in nestloop.
<header class="secreportChartHeader">
<span class = "secreportChartHeaderTitle">
<div id="Global" class ="headerglobal">
<div id="left" >log severity by Datenumber</div>
</div>
</span>
<header>
I would like to change 'log severity by dataenumber' : color,size,font.
var header = $element[0].children[0]; // it contains the above html tags
I am tried like this getting an error blocks are nested too deeply.
var chartHeader = header.getElementsByClassName('header');
for(var i=0; i<chartHeader.length; i++) {
if(chartHeader[i].className === 'secreportChartHeaderTitle') {
chartHeader[i].style.color = 'red';
}
}
AngularJS has a small version of jQuery in it (jq Lite) that you could utilize for grabbing an element with a class name very easily with $('.secreportChartHeader')
See documentation here: https://docs.angularjs.org/api/ng/function/angular.element
From a code perspective, the main problem I see is that you are looking for an element with the class name 'header' which does not exist. If you want to grab the header element, just use the native angular element selector angular.element('header')
Hope that helps! Good Luck!

Classes acculumating when cloning a template for a data array

I've ran into a problem when cloning a template div to create elements for a dataset.
The problem is that classes accumulate between creating the elements for each data record.
Example JS:
$(document).ready(function(){
var data = [
{cls: 'test1',text:'test1'},
{cls: 'test2',text:'test2'},
{cls: 'test3',text:'test3'}
];
for(var x in data)
{
var item = $('#itemTemplate').clone().removeClass('template');
item.addClass(data[x].cls).html(data[x].text);
$('#test-container').prepend(item);
}
});
And the HTML body:
<div id="test-container">
</div>
<div id="itemTemplate" class="template">
</div>
This produces:
<div id="test-container">
<div id="itemTemplate" class="test1 test2 test3">test3</div>
<div id="itemTemplate" class="test1 test2">test2</div>
<div id="itemTemplate" class="test1">test1</div>
</div>
Notice the test1 test2 test3 where it should just be test3. Am I missing something or just got it plain wrong?
Tested in jQuery 1.7 & 1.6.4.
you should also remove the id from the cloned elements. else it doesn't know which one he needs to clone
item.addClass(data[x].cls).html(data[x].text).removeAttr("id");
Changing the following line will remove all classes on the element, allowing you to add just the one you want.
var item = $('#itemTemplate').clone().removeClass()
The underlying problem is due to the fact that you're cloning the element whilst maintaining the ID. The next time you use the ID selector you're picking up multiple elements. Therefore t would also be worth changing the ID of the cloned element before appending it:
var item = $('#itemTemplate').clone().attr("id", data[x].text).removeClass()

Cleaner way to write element.parent().parent().parent().parent().parent()

If I need to select 10-th parent, is there a cleaner way, then repeating .parent() 10 times?
$('#element_id').parent().parent().parent().parent().parent().parent().parent().parent().parent().parent();
If there's a selector that represents the target you're after, then use .closest() or .parents().
$('#element_id').closest('.someClass');
$('#element_id').parents('.someClass:first');
...but both of these will return the first match found. The proper solution will depend on your actual HTML markup.
(Note that .closest() also evaluates the original element, while parents() starts with the first ancestor.)
Also keep in mind that browsers make HTML corrections. So if you're traversing from inside a <table> that has no <tbody> to an element outside the <table>, doing x number of .parent() may give different results in different browsers.
The following post here uses this implementation:
jQuery.fn.getParent = function(num) {
var last = this[0];
for (var i = 0; i < num; i++) {
if(!last) break;
last = last.parentNode;
}
return jQuery(last);
};
// usage:
$('#myElement').getParent(3);
so your usage would simply be:
$('#element_id').getParent(10);
If you truly need to get the 10th parent, and you are unable to use a selector to get there, the smoothest way would probably be something like this:
$('#element_id').parents().eq(9);
I've used this code:
var position = $("#test").parents("div").length - 10;
$("#test").closest("div:eq(" + position + ")").append("here!!!");
with that HTML :
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<span id="test">here</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Yes that is 11 div. so running the code should stop at the 10th div and append here!!!
I'm sure this code could be even more clean.
No need to add class.
Edit:
I used 11 DIV so you can see it's not going to the very first one, it actually stop at the 10th.

Categories

Resources