Add an id to a dynamically created element - javascript

I'm trying to add an id to an element that I create dynamically using javascripts' document.createElement() method. Basically I want to create an iframe in my html document and at the same time give that newly created element an id.
Here's my code so far. I've figured out how to put the element in the DOM and all that, i just need the id.
function build(content){
var newIframe = document.createElement("iframe");
var newContent = document.createTextNode("Hello World!");
newIframe.appendChild(newContent);
var element = document.getElementById("container");
document.body.insertBefore(newIframe, element);
document.getElementsByTagName("iframe").id = "active";
};
As you can probably see, I have tried to give it an id at the very end. Problem is, it doesn't work.
So if anyone has any idea of what is wrong here, or an alternative way of doing what I want to do, please feel free to express yourself. Many thanks!

Just add an attribute (id is an attribute) to that element directly, like this:
var newIframe = document.createElement("iframe");
newIframe.id = 'active';
... although it looks quite strange to have id equal to active (too generic for a unique identifier).
Your current approach doesn't work because document.getElementsByTagName("iframe") returns a collection of elements - NodeList or HTMLCollection (it's browser-dependant). While you can assign a value to its id property, it won't do what you mean to. To make it work, you can adjust it this way:
document.getElementsByTagName("iframe")[0].id = "active";
... but, as shown above, there's a better way.

newIFrame.setAttribute("id", "something");

Related

Get text value from especific class in web site

I want to know if it is possible to go to a site and retrieve the text of an element
i think something like
a = page("www.site.com")
b = a.getElementByClass("name")
console.log(b.text)
this is possible?
Yes. It's called the innerText property. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
That depends,
If you want to get the innerText of the elements, then
let elements = document.getElementsByClassName("YourClassName");
for(let i=0;i<elements.length; i++){
/*doSOmething*/
console.log(elements[i].innerText);
}
Many elements may have same className. So, if you want to access some specific Element, then you should either know the index of the element or you need to use id for the element.
let element = document.getElementById("YourElementId");
/*doSOmething*/
console.log(element.innerText);

.appendChild() an HTML element on click

I wanted to copy an entire row including its' siblings and contents on button click. When I click the button the element, it appears in the console but doesn't append to the page. This is my code:
It doesn't show any error messages. I've tried innerHTML/outerHTML or append() it doesn't work.
$(document).ready(function() {
$('#addSubFBtn').on('click', function() {
var itm = document.getElementById("trFb");
var wrapper = document.createElement('div');
var el = wrapper.appendChild(itm);
document.getElementById("tbFb").append(el);
console.log(el);
});
});
Seems like what you're trying to do is clone the item after you get it from your document. W3schools website explains how to accomplish this. Check out the link: https://www.w3schools.com/jsref/met_node_clonenode.asp
Once you clone the node, [appendchild] should work as intended
Not sure (as said without seeing related HTML) but i see flaw in your logic:
var itm = document.getElementById("trFb");
still exist on the document(so in the page) so you've to retrieve it before you want to add/move it to another place.
using .removeElement will return you removed element(or null if no element matche the selector) so correct script should be:
var itm=document.getElementById("trFb").parentNode.removeChild(document.getElementById("trFb"));
as shown here to remove element you've to use method on to parent element.
So you can add it to any other element existing.
For more specific use or element created in global JS variable (such an createElement not yet appended) you can see :document.createDocumentFragment(); as explained here https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment

How to duplicate a div in JavaScript

I was wondering how I can duplicate a DIV element a few times through JavaScript without duplicating the DIV in my html code?
Let's assume the you selected the div doing something like:
var myDiv = document.getElementById("myDivId");
The DOM API contains a cloneNode method which you can use
var divClone = myDiv.cloneNode(true); // the true is for deep cloning
Now you can add it to the document
document.body.appendChild(divClone);
Here is a short self contained code example illustrating this

Get the id of a the item that is clicked

I have this html code:
<b class = "edit" id = "foo1">FOO</b>
<b class = "edit" id = "foo2">FOO2</b>
<b class = "edit" id = "foo3">FOO3</b>
And I have this code in jQuery:
$('b.edit').click(function(){
//GET THE ID OF THE b.edit: e.g foo1, foo2, foo3
$('.editP').focus();
});
How can I get the id value of the b.edit, as there are multiple instances of b.edit, and I want to get the specific id of the one clicked? How can I do this?
Thanks, Sorry, I am pretty new to javascript.
I'm assuming from your sample code that you're using jQuery? If so you can get the id as follows:
$('b.edit').click(function(){
this.id;
});
EDIT:
The direct reference to the attribute is indeed more efficient if all that is required is simply the id.
Also can be obtained from the jQuery object:
$('b.edit').click(function(){
$(this).attr('id');
});
Sample fiddle: http://jsfiddle.net/5bQQT/
Try with this:
$('b.edit').click(function(e){ //When you use an event is better
//send the event variable to the
//binding function.
var id = e.target.id; //get the id of the clicked element.
/*do your stuff*/
$('.editP').focus();
});
try this. You can use keyword "this" to retrieve the attr ID...
$('b.edit').click(function(){
alert($(this).attr("id"));
});
$('.edit').click(function(){
var theId = $(this).attr('id');
}
This will get you the ID of anything clicked with a class of .edit
$('.edit').live('click', function() {
alert( this.id );
});
Sample
http://jsfiddle.net/ck2Xk/
When passing a click handler in JQuery, you actually have a reference to something called an event object. This event object has a property called target, which is a reference to the element that was clicked.
$('b.edit').click(function(eventObject){
eventObject.target // this is the element that was clicked.
});
Since you have a reference to the target element, you can do whatever you like. In this case, you could just access eventObject.target.id.
Since nobody has shown the simplest method yet that doesn't even need jQuery to get the id:
$('.edit').click(function() {
alert(this.id);
});
I never understand why people use jQuery for getting simple attributes which involves two jQuery function calls (and a bunch of overhead to create a jQuery object) instead of one direct attribute reference.
something like this:
var id = $(this).attr('id');
More clearly:
$('b.edit').live('click', function(){
var id = $(this).attr('id');
// in this scope this.id works too
// var id = this.id;
});
This is called event delegation in Javascript. More info can be found in Zakas blog http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/
The idea in few words is you attache the event to a parent node and then waiting for some event on the child node. In the example below I attach the onclick event to the document itself. Then inside the event handler you will write a switch statement to check the clicked element id, then do what you want to do for that element
document.onclick = function(event){
//IE doesn't pass in the event object
event = event || window.event;
//IE uses srcElement as the target
var target = event.target || event.srcElement;
switch(target.id){
case "foo1":
foo1();
break;
case "foo2":
foo2();
break;
case "foo3":
foo3();
break;
//others?
}
};
//some dummy handlers
var foo1 = function(){
alert("You clicked foo1");
};
var foo2 = function(){
alert("You clicked foo2");
};
var foo3 = function(){
alert("You clicked foo3");
};
For how to implement event delegation in jQuery you can check http://api.jquery.com/on/#direct-and-delegated-events
Even though this is not a real answer to your question. I will try to explain why what your asking is not the way to go. Since you are new especially, since learing bad practices could be hard to unlearn. Allways try to search for an ID before finding an element by its Class. Also try to avoid giving every element the same class (and in this case ID to), just give it an encapsulating parent.
Furthermore, the id of an element is really specific and should preferably used to find / select / bind events to. An id should usually be unique for this to work, so in your case a couple of things could be optimized, lets say like:
<div id="foo">
<b id="1">Foo</b>
<b id="2">Other foo</b>
<b id="3">Some foo</b>
</div>
Now if you want to know which was clicked there are multiple ways to accomplish it, but a nice one is simply binding a parent its children (i.e <div id="foo"> .. </div>). This way you can alter the structure of your pretty fast, without changing all the classes and id's.
With jQuery you can get the attribute id using the .attr() function. However I told you the id was pretty specific and thus has its own rights in javascript world. An id can also be directly targeted ('DOMelement.id', but this would be too much to explain for now)
In two ways the <b> can be targetted:
Example a)
var b_elements = $("#foo").children();
Example b)
var b_elements = $("#foo").find('b');
We can add jQuery (or javascript events) to these found elements. The nice thing about jQuery is that it simplifies alot of work. So in your case if you would like to know an id of a certain clicked <b> field you could use a very verbose way:
b_elements.click(function()
{
var clicked_element = $(this);
alert(clicked_element.attr('id'));
});
Verbose because you can do it much much shorter, but who cares about a few bytes when your learning and this makes remembering functions and events alot easier. Say you wanted to get the class edit by finding the where you knew the id that was clicked:
b_elements.click(function()
{
var clicked_element = $(this);
alert(clicked_element.attr('class'));
});
And to conclude, the id of an element is ment to be unique because it makes searching through big documents alot faster. Also don't forget to look and learn plain javascript, as it helps coding in jQuery alot too, but not the other way around. Your given question would require a for loop in plain javascript since it cannot do a lookup by class nor id nor have they have a common parent.
Good luck with learning :)

How to get attributes of container in jquery?

How can I get attributes values from an container using jquery ?
For example:
I have container div as:
<div id = "zone-2fPromotion-2f" class = "promotion">
here how can I get attribute id value using jquery and than how can I trim the value to get component information ?
update : how can i get attribute values ?
UPDATE: If I have multiple components on page with same div information than how would I know what attribute value is for which component ?
Thanks.
First, that seems to be a ridiculously long ID -- I'm sure it could be made much shorter while still retaining its uniqueness.
Anyway, on to the answer: First you need a way of accessing your "container" div. Typically, one might use a class or ID to get an element. For example, you could "select" this div with the following call to jQuery:
var container = jQuery('#zone-3a...'); // Fill in ... with really long ID
But, since you're asking how to retrieve the ID, I'm presuming that selecting it via the ID is not an option. You could also select it using the class, although it's not guarenteed to be the only element on the page with that class:
var container = jQuery('.promotion');
There are other ways to narrow down the search, such as:
jQuery('div.promotion');
jQuery('div.promotion:first');
Once you have a reference to your "container", you can retrieve the ID like so:
container.attr('id'); // => zone-3a...
// or:
container[0].id; // => zone-3a...
So assuming your div looks like this.
<div id="foo"/>
You could get the ID attribute by using the attr method.
$("div").attr("id);
That assumes that you only have one div on the page. Not really sure what component information you are looking to get?
You read node attributes with the attr() method.
var id = $( '.promotion' ).attr( 'id' );
In terms of parsing that ID for any other arbitrary information, I can't say since it looks like you're using some sort of proprietary format of which I have no knowledge.
loop thru and get all divs with the class promotion and get the id of each...
$('div.promotion').each(function(){
var attr = $(this).attr('id'); // or whatever attribute
});
or single
var myDivClass = $('zone-3a-2f-2f-2fPortal-2fPages-2fHome-2fZones-2fLeft-2f-7ccomponent-3a-2f-2f-2fSpm-2fComponents-2fPromotion-2f').attr('class');
or another single
var myDivID = $('.promotion').attr('id');

Categories