How can I use javascript variable as html's div id? - javascript

<script>
Var x="....";
<\script>
<div id = x>
Some content
<\div>
As u can see in the above code I want to use the variable x as div's id but its not working.
Any suggestions plz...

You have to set the element’s id in your javascript code. See the code snippet below, the text apppears red because the javascript attaches the id red, stored in your variable x, to the div.
var x = 'red';
document.getElementsByTagName('div')[0].id = x;
#red {
color: red;
}
<div>Some content</div>

It is not impossible.
If you want to add id to elements dynamically, you should wait until document will be loaded. Then run script like:
var el = document.querySelector() // with some selector rule
// and set attribute 'id'
el.id = 'myId';
Perhaps you should tell what you want to do and find another way

Related

Removing and creating HTML elements with same id using Javascript

I have a button that, when pressed, executes something like
function click(){
element = document.getElementById("element");
element.parentNode.removeChild(element);
var newelement = document.createElement("div");
body.appendChild(newelement);
newelement.id = "element";
}
I have also tried using element.outerHTML = "" instead of removeChild with no success. Before adding the bit about deleting the previous element with the id "element" things worked fine on the first click and an div named "element" was appended to the body. (Of course, on the second click, another element named "element" is appended, and I want to keep the id unique to one element.) Now, with the bit about removing previous elements, my button.onClick doesn't even do anything.
Another important piece of context: I'm trying to do this for elements that are generated using user input, so there's no guarantee on how many of these things are made--I just want them deleted when the user wants to generate more of them.
On the first click, I'm attempting to remove an empty element. Does that break something?
body does not exist in the scope you've provided and would throw an exception. I would try:
var body = document.querySelector("body");
See this for a example using your code:
https://jsfiddle.net/k0wL4y7p/2/
Also make sure you use var on all local variables so they are not declared globally. See below to learn about variable scope:
When to use var in Javascript
How about this... don't remove the Parent Element (Div1); instead to remove the children. Then, create the child and append it to the parent element.
Note: you must iterate over it to remove all child nodes & for p element id p1/p2 generate dynamic id or use class if you need it.
Your JS:
$(document).ready(function() {
$("#btn1").click(function() {
var element = document.getElementById("div1");
while (element.firstChild) {
element.removeChild(element.firstChild);
}
var para = document.createElement("p");
var node = document.createTextNode("New element after click.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
});
});
I prefer JQuery - no loop
$(document).ready(function(){
$("#btn1").click(function(){
$("#div1").empty();
$("#div1").append(" <p>Appended element after click</p>");
});
});
Your Html
<body>
<div id="div1">
<p id="p1">Paragraph element before click.</p>
<p id="p2">Another paragraph beofre click.</p>
</div>
<button id="btn1">Remove </button>
</body>
Hope it helps.

Getting Element

I am new to this and I have this element and I have to somehow "get it". There are few more element above it, there's just an element I need:
<a class="btn_green" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
<span>Some text</span>
</a>
Thanks for help!
$('a.btn_green') will return an array of you could use the Array index to access the proper value if the index is known and does not change
var $a = $('a.btn_green');
var el = $a[2];
You can use getElementsByClassName.
document.getElementsByClassName('btn_green')
This will return an array of all the elements that match. If you have only one element you can access it at index 0.
document.getElementsByClassName('btn_green')[0]
If you added an ID to the element,and then use getElementById
<a id="YOUR_ID_HERE" class="btn_green" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
document.getElementById('YOUR_ID_HERE')
You can do something like this in standard JS you would do something similar to this:
var button = document.getElementsByClassName('btn_green');
If you're just looking to get that specific element I would suggest adding an id
<a class="btn_green" id="myButton" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
<span>Some text</span>
</a>
And here is the JS
var button = document.getElementById('myButton');
Details are commented in the Snippet. The anchor in OP's code is atrocious so I made the markup simpler, but the code provided here will work an any anchor(s) under certain conditions described below.
SNIPPET
/* Plain JavaScript */
/* If there is only one element that has the class="btn_green" */
// By className
var btnByClassName = document.querySelector(".btn_green");
/* If it is the only link (anchor)
*/
// By tagName
var btnByTagName = document.querySelector("a");
/* If theres more than one element with the class="btn_green" */
// By className
var btnsByClassName1 = document.querySelectorAll(".btn_green");
// or
var btnsByClassName2 = document.getElementsByClassName("btn_green");
/* The two methods above will collect all elements with the
specified className. The group of elements collected is known
as a HTML Collection or NodeList. If you need to specifically
target one of them out of a group, say like the 2nd one, you have
to count from 0. Ex. the second element in a NodeList would be 1.
*/
/* Continuing from the previous example above, we can single out a
single element by placing the 0 count number of that element:
*/
var btnsByClassNameA = document.querySelectorAll(".btn_green")[1];
//or
var btnsByClassNameB = document.getElementsByClassName("btn_green")[1];
/* A different type of NodeList/HTML Collection can be had by
targeting the tagName, this example we are targeting the first
anchor:
*/
var btnsByTagName1 = document.querySelectorAll("a")[0];
//or
var btnsByTagName2 = document.getElementsByTagName("a")[0];
/* Note: Although these methods are able to get a group of
elements, they are able to get an element if it is the only
one of it's kind by using [0].
*/
/* jQuery */
/* jQuery makes it easier and does most of the thinking for us.
You must make sure that your page has the jQuery library loaded.
Look at the HTML section below, you'll see a <script... tag. You
must have that tag inside the <head></head> or before the </body>
otherwise you code will not function.
*/
/* Note the variable has a $ prefix. This is optional and it's
purpose is to show other developers that the variable represents a
jQuery Object.
*/
// By className
var $btnsByClassName = $(".btn_green");
// By tagName
var $btnsByTagName = $("a");
/* This part is not part of the question, it is just to show that
these references are working */
$btnsByTagName.on('click', aTonOfStuff);
function aTonOfStuff() {
btnByClassName.style.backgroundColor = "black";
btnByTagName.style.color = "lime";
for (let i = 0; i < btnsByClassName1.length; i++) {
btnsByClassName1[i].style.fontSize = "40px";
btnsByClassName2[i].style.fontVariant = "small-caps";
}
btnsByClassNameA.style.backgroundColor = "#0E0";
btnsByClassNameB.style.color = "#000";
btnsByTagName1.style.lineHeight = "2";
btnsByTagName2.style.textDecoration = "overline";
$btnsByClassName.fadeOut("slow");
$btnsByTagName.fadeIn("slow");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click any link.</p>
<a class="btn_green" href="#/">First Green Button Anchor Link</a>
<a class="btn_green" href="#/">Second Green Button Ancor Link</a>
Something like $('a.btn_green') would "get" that <a> element but it is not guaranteed to get it uniquely. You may need to use something like the :nth-child pseudo-selector to do this if you cannot modify the source. Without more context it is impossible to say what a selector would be that would uniquely retrieve either the <a> or the <span> element.
Here is a jQuery tutorial and here is a CSS selector reference, just in case you need them.
Edit
One weird thing happening on the page is $ no longer seems to be bound to jQuery. They must be loading something which uses $ after jQuery which is causing selectors like $('a.btn_green') to return null. You can replace $ with jQuery instead.
I tried the using jQuery('.btn_green_white_innerfade.btn_medium') to find the element, but it looks like there are three elements on the page which share that selector. So I looked further up in the source and found that the button I think you want is within a div with the id market_buyorder_info. This led me to the following code to get the element uniquely:
jQuery('#market_buyorder_info').find('.btn_green_white_innerfade.btn_medium')
And this code to trigger a click in the console:
jQuery('#market_buyorder_info').find('.btn_green_white_innerfade.btn_medium').click()

HTML id tag conflict with array member

My page has a bunch of id's on <div> elements - xx1, xx2, xx3, xx4.
I also have an array, idIndex = [xx1, xx2, xx3, xx4], which is used to construct an id tag using jQuery, as follows:
$("#" + idIndex[2]).text("New text here");
Unfortunately, this does not work. Javascript dereference the actual ID in the page instead of constructing a tag, and tells me that idIndex[2] is actually [object HTMLDivElement], so that the jquery command does not work.
How do I build up the name of the id tag?
If you have a div with an ID of xx1, then there is a global variable called xx1 which is the element in question.
When you write idIndex = [xx1], you're building up an array of DIV elements. If you want to build up an array of string IDs, you need idIndex = ["xx1"] etc. The quotes are important.
That said, you already have an array of elements. Instead of re-selecting the element from the DOM by their ID, just wrap the element itself in a jQuery object:
var $el = $(idIndex[2]);
By way of explanation, here's a single div with ID of xx1. You can see there is a xx1 variable and that wrapping it in $() works fine:
console.log(xx1);
$(xx1).text("Test 123")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="xx1"></div>
Try using $(idIndex[2]).text("text");
Here is the working code :
JS:
<script>
$(document).ready(function(){
var idIndex = ["xx1", "xx2", "xx3", "xx4"];
$("#" + idIndex[2]).text("New text here");
});
</script>
HTML:
<div id="xx1"></div>
<div id="xx2"></div>
<div id="xx3"></div>
<div id="xx4"></div>

getting the value of a div in jquery?

i wanted to get the value of a hidden div in jquery i.e.
<div id="text">hello i am the value, you want</div>
and i want insert this value into a another div in jquery i.e.
$('#bio').html($value);
EDIT:
i forgot to mention that it had to be the text within the block div sorry i.e. its parent
<div class="block" id="status_13">
<div id="text">.......</div>
</div>
i.e.
$('.block').click(function(){
$('#bio').html($('$text').html());
If your #text element contains HTML you might want to do:
$('#bio').html($('#text').html());
If you are only concerned with the literal text of #text then you can do:
$('#bio').text($('#text').text());
Of course, if you want to store the text in a variable first, you can do so:
var textValue = $('#text').text();
$('#bio').text(textValue);
In regard to your later edit:
$('.block').bind('click', function() {
var thisTextValue = $(this).children('.text').first().html();
$('#bio').html(thisTextValue);
});
Notice that I assumed the child div is marked with a class and not an id. Based on your description, it sounds like you have multiple "block" elements which each contain a "text" element. If that is the case, then $('#text') will always return the first "text" element in the document; IDs are unique in the document.
Don't use $ for variables (like $value), just value
var value = $('#text').html();
Did you try
$('#bio').html($('#text').html());
I think this would work
//get the value from hidden field and store it in the variable 'valueYouWant'
var valueYouWant = $("#text").html();
//set it in other field
$("#bio").html(valueYouWant);
edit:
More information can be found here

How to access HTML element without ID?

For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
Thanks!
function findFirstDescendant(parent, tagname)
{
parent = document.getElementById(parent);
var descendants = parent.getElementsByTagName(tagname);
if ( descendants.length )
return descendants[0];
return null;
}
var header = findFirstDescendant("header-inner", "h1");
Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on descendants to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).
If you were to use jQuery as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant):
var element = $('#header-inner h1');
Using a library like JQuery makes things like this trivial compared to the normal ways as mentioned in other posts. Then once you have a reference to it in a jQuery object, you have even more functions available to easily manipulate its content and appearance.
If you are sure that there is only one H1 element in your div:
var parent = document.getElementById('header-inner');
var element = parent.GetElementsByTagName('h1')[0];
Going through descendants,as Shog9 showed, is a good way too.
It's been a few years since this question was asked and answered. In modern DOM, you could use querySelector:
document.querySelector('#header-inner h1').textContent = 'Different text';
<div id='header-inner'>
<div class='titlewrapper'>
<h1 class='title'>
Some text I want to change
</h1>
</div>
</div>
The simplest way of doing it with your current markup is:
document.getElementById('header-inner').getElementsByTagName('h1')[0].innerHTML = 'new text';
This assumes your H1 tag is always the first one within the 'header-inner' element.
To get the children nodes, use obj.childNodes, that returns a collection object.
To get the first child, use list[0], that returns a node.
So the complete code should be:
var div = document.getElementById('header-inner');
var divTitleWrapper = div.childNodes[0];
var h1 = divTitleWrapper.childNodes[0];
If you want to iterate over all the children, comparing if they are of class “title”, you can iterate using a for loop and the className attribute.
The code should be:
var h1 = null;
var nodeList = divTitleWrapper.childNodes;
for (i =0;i < nodeList.length;i++){
var node = nodeList[i];
if(node.className == 'title' && node.tagName == 'H1'){
h1 = node;
}
}
Here I get the H1 elements value in a div where the H1 element which has CSS class="myheader":
var nodes = document.getElementById("mydiv")
.getElementsByTagName("H1");
for(i=0;i<nodes.length;i++)
{
if(nodes.item(i).getAttribute("class") == "myheader")
alert(nodes.item(i).innerHTML);
}
Here is the markup:
<div id="mydiv">
<h1 class="myheader">Hello</h1>
</div>
I would also recommend to use jQuery if you need a heavy parsing for your DOM.

Categories

Resources