How to set text of div to its Id in javascript - javascript

what I am trying to achieve is set the text of a div tag to the name if its ID from javascript. I have tried this;
mydiv.getElementsByClassName("divDesign").innerHTML = document.getElementsByClassName("divDesign").getElementById;
However, this returns undefined in the div tag instead of writing its id.

Using getAttribute() method:
For the first div with ClassName = 'divDesign':
document.getElementsByClassName('divDesign')[0].innerHTML = document.getElementsByClassName('divDesign')[0].getAttribute('id');
For all divs with ClassName = 'divDesign':
var mydivs = document.getElementsByClassName('divDesign');
for (var index = 0; index < mydivs.length; index++) {
mydivs[index].innerHTML = mydivs[index].getAttribute('id');
}
<div class="divDesign" id="someId"></div>
Using id() property:
For the first div with ClassName = 'divDesign':
document.getElementsByClassName('divDesign')[0].innerHTML = document.getElementsByClassName('divDesign')[0].id;
For all divs with ClassName = 'divDesign':
var mydivs = document.getElementsByClassName('divDesign');
for (var index = 0; index < mydivs.length; index++) {
mydivs[index].innerHTML = mydivs[index].id;
}
<div class="divDesign" id="someId"></div>
Documentation:
MDN

Yo need to specify an index of the element as document.getElementsByClassName("divDesign") returns a nodes list.
document.getElementsByClassName("divDesign")[0].innerHTML =
document.getElementsByClassName("divDesign")[0].id;
<div class="divDesign" id="iAmAnId"></div>

Related

Javascript Add Custom active Class inside loop

I have two loop like below you can see and need to add a custom active-numberHere class to the first image of each div with a specified number.
for example, if div class number is img-4 so add class active-4 to first img tag.
But I have some problems in code that you can see in the attached image.
in the first div image have the correct class.
but in other div image have extra active like active-4 active-3 and ...!
How can I solve this problem?
// LOOP Create Image Div
let numDiv = 5;
for (k = 0; k < numDiv; k++) {
//Add div area inside Div(products)
let imgPart = `<div class="img-${k} shoe-part"> </div>`;
document.querySelector(".products").insertAdjacentHTML("afterbegin", imgPart);
// LOOP Create Image List Inside Divs
let numImg = 3;
for (j = 0; j < numImg; j++) {
//Add Image List Inside Above Div(shoe-part)
let imgList = `<img class="res-img" src="img/image-${k}.png">`;
document.querySelector(".shoe-part").insertAdjacentHTML("afterbegin", imgList);
}
$('.shoe-part img:first-child').addClass(`active-${k}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="products">
</div>
Simple way to do this by jquery is to use html() and prepend() or append()
for add class you can use a simple if statement inside the loop
// LOOP Create Image Div
let numDiv = 5;
for (k = 0; k < numDiv; k++) {
//Add div area inside Div(products)
var DivPart = `<div class="img-${k} shoe-part"></div>`;
// LOOP Create Image List Inside Divs
let numImg = 3;
let ImgPart = '';
for (j = 0; j < numImg; j++) {
//Add Image List Inside Above Div(shoe-part)
var AddClass = (j === 0) ? 'active-'+k : ''; // shorthand if statement to add the class only when j = 0
ImgPart += `<img class="res-img ${AddClass}" src="img/image-${k}.png">`; // add all the images in the valriable ImgPart by using += it means sum/combine/addto
}
DivPart = $(DivPart).html(ImgPart); // update DivPart with the whole div with images in it
$('.products').prepend(DivPart); // prepend the DivPart to the product div
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="products">
</div>

How scan all <span> tags of a page and get or set a content?

I have this following code that scans all <input> tags of a page and then you are able to set you to get a value to this tag.
var input = document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
input[i].value = "123";
}
Now, how can I do the same with a <span> tag, which I already know does not have a property called value?
Your question was somewhat confusing, but I'll give my best answer:
Just take your code for the inputs, and change a few key componenents:
var span = document.getElementsByTagName('span');//Replace "input" with "span"
for (var i = 0; i < span.length; i++) {//Again, replacing "input" with "span"
var textInsideTheSpan = span[i].textContent;//Reading text inside span
span[i].textContent = "Your text here";//Writing text to the span
}
The key here is in the .textContent, a property of the javascript Node object, which can be read or written to, depending on your application. Everything else simply replaced "input" with "span".
Just use following:
var spans = document.getElementsByTagName('span');
for (var i = 0; i < spans.length; i++) {
var text = spans[i].innerHTML;
if (text.length == 0) {
spans[i].innerHTML = i; //Some text
}
}
You can use Node.textContent to set the text inside span:
var input = document.getElementsByTagName('span');
for (var i = 0; i < input.length; i++) {
input[i].textContent = "123";
}
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>

Strange Javascript for loop behavior when using Jquery append

I'm probably missing/doing something silly, but I can't seem to work this out:
Here's a fiddle showing the problem:
https://jsfiddle.net/jhqjmcn4/1/
Note that you will need to open your console to see what is happening.
Basically, in this example, I have two functions containing a for loop that are identical to each other except the second one contains a JQuery append.
The goal of the function is to get the html elements from within a string, which works fine in the first function, but not the second.
As can be seen in the console, this causes anything that is not a text node to be ignored and not added to the list. In this case, the b and p tags are not being included.
Here is the code again:
JS:
function parse_text(text) {
var div = document.createElement("DIV");
div.innerHTML = text;
var elements = div.childNodes;
var container = jQuery("#container");
var list = [];
for (var i = 0; i < elements.length; i++){
var element = elements[i];
list.push(element);
console.log("First", list);
}
}
function parse_text_two(text) {
var div = document.createElement("DIV");
div.innerHTML = text;
var elements = div.childNodes;
var container = jQuery("#container2");
var list = [];
for (var p = 0; p < elements.length; p++){
var element = elements[p];
list.push(element);
console.log("Second", list);
container.append(element);
}
}
var text = "Here is <b>some</b> text with <p>html</p> in it";
parse_text(text);
parse_text_two(text);
html (irrelevant):
<div id="container">
</div>
<div id="container2">
</div>
Thanks in advance.
I suppose you need to have a Array.prototype.filter() method to get the html elements:
function parse_text_two(text) {
var div = document.createElement("DIV");
div.innerHTML = text;
var elements = [].filter.call(div.childNodes, function(el) {
return el.nodeType !== 3;
});
var container = jQuery("#container2");
var list = [];
for (var p = 0; p < elements.length; p++) {
var element = elements[p];
list.push(element);
console.log("Second", list);
container.append(element);
}
}
var text = "Here is <b>some</b> text with <p>html</p> in it";
parse_text_two(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
</div>
<div id="container2">
</div>
You can check updated fiddle here jsfiddle.net/bharatsing/jhqjmcn4/3/
Its return same result for both methods in console as per you want.
function parse_text_two(text) {
var div = document.createElement("DIV");
div.innerHTML = text;
var elementsOrg = div.childNodes;
var elements = Array.prototype.slice.call(elementsOrg);;
var container = jQuery("#container2");
var list = [];
for (var p = 0; p < elements.length; p++){
var element = elements[p];
list.push(element);
console.log("Second", list);
container.append(element);
}
}
The issue I saw by putting a debug point inside the loop was this:
The container.append(element); statement was actually modifying the elements array and was removing the appended element from the array. Which meant that in the loop for various values of 'p' the elements array looked like this:
p = 0 -> elements : [ text, b, text, p, text ] // text node at 0 picked
p = 1 -> elements : [ b, text, p, text ] // text node at 1 picked
p = 2 -> elements : [ text, p, text ] // text node at 2 picked
That is why the loop only ran 3 times instead of the original length of the elements array , i.e. 5.
This probably happens because jQuery 'moves' the node from its original place to the container div.
You can either clone the element node and then append into the container:
function parse_text_two(text) {
var div = document.createElement("DIV"),
p,
element,
elements,
container = jQuery("#container2"),
list = [];
div.innerHTML = text;
elements = div.childNodes;
for (p = 0; p < elements.length; p++){
element = elements[p];
list.push(element);
console.log("Second", list);
container.append($(element).clone());
}
}
Or use a while loop as suggested in Venkatesh's answer. Anyway, it is always better to know the root cause. :)
Hope this helps.
In second function in each loop comment this line container.append(element);

Div's are being generated dynamically and even the (obj.search) fetches the data but nothing is being displayed in it. How do i display the data?

JS doesn't display the output
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.id = "div"+i;
divTag.className = "list";
document.getElementById('div'+i).innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
}
Image here
You missed adding the newly created element to the DOM. Example:
document.getElementById("yourDivContainer").appendChild(divTag);
Fiddle:
http://jsfiddle.net/mbpfgm49/
You need to append your div tags to some element (e.g: body), to make text appear on page
// Let's create some sample data
var obj = {
Search: []
}
var currentYear = (new Date).getFullYear();
for (var i = currentYear - 10; i <= currentYear; i++) {
obj.Search.push({
Title: 'Test',
Year: i
})
}
// Here goes your code fixed
for (var i = 0; i < obj.Search.length; i++) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.className = "list";
divTag.innerHTML = obj.Search[i].Title + ' ' + obj.Search[i].Year;
document.body.appendChild(divTag);
}
Yes, you have to add the element to the DOM.
More basically, it is an anti-pattern to construct IDs for elements and use those as the primary means for referring to elements, by means of calling getElementById at every turn. I guess this approach is one of the many lingering after-effects of the jQuery epidemic.
Instead, keep references to elements directly in JS where possible, and use them directly:
for (var i = 0; i < obj.Search.length; i++){
var divTag = document.createElement("div");
divTag.className = "list";
parent.appendChild(divTag);
^^^^^^^^^^^^^^^^^^^^^^^^^^ INSERT ELEMENT
divTag.innerHTML+=obj.Search[i].Title+obj.Search[i].Year;
^^^^^^ REFER TO ELEMENT DIRECTLY
}
To be absolutely pedantically correct, what you are creating is not a "tag", it's an "element". The element is the DOM object. The "tag" is the div which characterizes the element type.

Select all element with same tag name using javascript and highlight content partially

I made a code that should highlight searched string but it is not working.
Here is the code:
<body>
<div>div is here</div>
<div id="divid">
<div>this is a div 1</div>
<div> this is a div 2</div>
<div> this is a div3</div>
</div>
<div> another div is here</div>
</body>
Here is a javascript code.
function checkit(){
var hlWord = "div";
var nregex = new RegExp(hlWord,"gi");
var div = document.getElementById("divid").getElementsByTagName('div');
for(var i=0; i <= div.length; i++){
var div1 = div[i].innerHTML;
var rword = div1.replace(nregex,"<b>"+hlWord+"</b>");
div1.innerHTML = rword;
}
}
There are begginer mistakes in your code. Let me correct them:
function checkit(){
var hlWord = "div"; //Define string that will be emphasized by <b> tag
var nregex = new RegExp(hlWord,"gi");//Create global, case-insensitive regexp
var div = document.getElementById("divid").getElementsByTagName('div'); //Get element collection of divs in div#divid
for(var i=0; i < div.length; i++){ //Loop through my element collection
var div1 = div[i].innerHTML; //Get the innerHTML of on of the divs
var rword = div1.replace(nregex,"<b>"+hlWord+"</b>"); //Surround my string with <b>
div[i].innerHTML = rword; //Change the innerHTML back
}
}
You used this for condition: i<=div.length. This is wrong. Do not forget, that we count from 0 so: [0, 1, 2, 3].length = 4. Last element for such array has index 3. The [] is an array literal.
By mistake, you assigned div1.innerHTML. div1 was a string. The element you want to change is div[i].
I made a JSFiddle too!
The problem with you code will be, amongst other problems, that nested div elements will be broken. You should use some kind of recursion if you want to highlight the word 'div'.
Here is such a function:
function highLight(term,root){
var allDiv = root.querySelectorAll('div'),
replacer = function(a){return '<span class="highlight">'+a+'</span>'};
for (var i=0; i<allDiv.length; i+=1){
if (allDiv[i].querySelectorAll('div').length){
highLight(term, allDiv[i]);
} else {
var re = RegExp('('+term+')','gi');
allDiv[i].innerHTML = allDiv[i].innerHTML.replace(re,replacer);
}
}
}
And here is a jsfiddle to play around with it
A more advanced jsfiddle
You have several errors: there you go:
http://jsfiddle.net/55U6j/1/
function checkit(){
var hlWord = "div";
var nregex = new RegExp(hlWord,"gi");
var divs = document.getElementById("divid").getElementsByTagName('div');
for(var i=0; i < divs.length; i++){
var div = divs[i];
var html = div.innerHTML;
var rword = html.replace(nregex,"<b>"+hlWord+"</b>");
div.innerHTML = rword;
}
}

Categories