jQuery insertBefore, Apend for dynamically created elements - javascript

Please take a look at code, it is working, it should add just one p tag, but for some reason it is inserting several p tags. P tags are not dynamically created, but some of the content in the p tag is created dynamically(just for info, if it is important).
jQuery("div.content").on("click", ".add", function (e) {
var ptag = jQuery('p.test-me');
ptag.insertBefore('.main-content');
return false;
});
I would just like to insert one p tag(not several) on click before other p tag with class .main-content.
Thank you in advance.

You can try this:
var ptag = jQuery('p.test-me').eq(0);
ptag.insertBefore('.main-content');

In your code as you are referring p elements with class name .test-me there might be possibility of retrieving multiple elements if you have p more than one p elements with that class name. As you said it is appending multiple p elements, it is confirmed that there are multiple elements with the class name .test-me. If you do not want more than one element to be appended, and very sure about what element to be append just use id instead of class name, else just get first element of element list.
// with id
var ptag = jQuery('#id-of-p').clone().attr('id','');
// with className but first element
var ptag = jQuery('.test-me').first(); or .eq(0);
// with id, but should have .test-me class name, then only append?
var ptag = jQuery('#id-of-p.test-me').clone().attr('id','');

Related

documentCreatElement(div) returns undefined when I try to select it's attribute

I created a div with the document createElement() function,
I added an id attribute to it by using the setAttribute() function,
Now am trying to retrieve the elements with the getElementbyId() function but it's returning undefined. My code looks like this:
//initially
var contact= document.createElement('div');
contact.setAttribute('id','contact-grid');
//later on
var to=document.getElementById('contact-grid')`
to.onclick=function(){
alert('contact clicked');
}
//The code above is not working
Console says: I cannot set onclick of undefined. Please kindly tell me what AI am doing wrong
In order to dynamically create and append elements we have to use below methods to achieve what we need. The GetElemenetById function is applicable only if you have applied the appended the newly created element.
document.createElement()- This method creates the HTML element with the tag name passed as parameter.
example :create a li element:-
var dynamicLi = document.createElement("li");
element.setAttribute()- This method is use to set attribute.
example - add id in the newly create li tag":-
dynamicLI.setAttribute("id","li1");
node.appendChild()- This method append a node to the end of the list of children of a specified parent node.
example - add newly created li tag to its parent ul tag:-
let ul = document.getElementById("dynamic-list"); // we get the parent node
ul.appendChild(li); // we append the li in the ul tag .
So, below is the working code snippet, using step defined above:
let ul = document.getElementById("Ul");
let li = document.createElement("li");
li.setAttribute('id','li1');
ul.appendChild(li);
let newlyElem =document.getElementById("li1"); //code to find newly created element by element by id after append child.

How to createText and append text to an existing element e.g. empty span?

Everywhere I've searched I've only found ways to append a textnode after creating a new element. For example, they'll create a new paragraph (p) element, and afterwards they append the textnode to that new paragraph. But I want to add a textnode to an existing element (in my case, an empty span).
Link to code for example and clarification
http://pastebin.com/K1EBMr4Z
<span class="span"></span> <!-- append textnode here -->
function newFunction(){
var textnode = document.createTextNode("OK");
// Append my `textnode` to the empty span here
}
Thanks in advance
As mentioned in the comment, you can add the text node as a child of the span using the appendChild() method.
For text you can also just set the innerHTML property of the span.
Both examples in a bin:
function newFunction(){
var span = document.getElementById('my-span');
var otherSpan = document.getElementById('my-other-span');
span.innerHTML = 'Yo this is text';
var textNode = document.createTextNode("OK");
otherSpan.appendChild(textNode);
};
newFunction();
https://jsfiddle.net/9pmhan8L/1/
It's simple. Use appendChild method.
function newFunction(){
var textnode = document.createTextNode("OK");
document.querySelector(".span").appendChild(textnode);
}
If you give the span an id, you can get it using document.getElementById() and then change the html within that element. Here's a link to a SO that does this. Also, here's some docs for innerHTML and getElementByID.
You need to select the node you want to append the textNode to first. Then, append the textNode to that selected node (in your case, the .span element).
<span class="span"></span>
function newFunction(){
var textnode = document.createTextNode("Hello World!");
// Select your existing element
var empty_span = document.querySelector('.span');
// Append the element
empty_span.appendChild(textnode);
}
newFunction();
Example jsFiddle as well.
Why not to use jQuery:
$('span').text('text');
or
$('span').html('<p>text</p>');
If you do not use it, use:
document.getElementsByTagName('span').innerHTM = '<p>text</p>';

How can I insert a tag <br> into another tag using JavaScript?

I want to put a <br> tag in the end of every <text></text> tag. I tried using
var para = document.createElement("br");
var element = document.getElementsByTagName("text");
element.appendChild(para);
but i think i can't use the element.appendChild for more than 1 tag. Am I right?
"...but i think i can't use the element.appendChild for more than 1 tag. Am I right?"
Right. There are two parts to your question.
First, you need to loop over the collection returned from getElementsByTagName(). It does not have the same set of methods and properties that individual elements have.
Second, to insert a br element into each text element, you need to create a new br element each time since a node can only be in one location in the tree at a time.
var elements = document.getElementsByTagName("text");
// loop over collection
for (var i = 0; i < elements.length; i++) {
// append a newly created `br` for each `text`
elements[i].appendChild(document.createElement("br"));
}
<text>foo</text>
<text>bar</text>

Best way to search for elements in innerHTML

I'm using innerHTML to get the inner HTML of an li element that is clicked. I would then like to search that HTML for some paragraph tags and find their value, is there a good way to do that? I can't rewrite any of the list's HTML, that's being generated elsewhere in the project but I do know the class names used for the tags. jQuery answers are fine.
The best way to 'search' the HTML is to use the DOM. Note that if the container element in which you want to search exists in your DOM already, you do not need to contruct a new dummy element and can just retrieve this parent node and use the same approach.
var el = document.createElement('div'),
someHtmlToSearch = '<div><p>test content in p</p></div>',
pContent;
el.innerHTML = someHtmlToSearch;
pContent = el.querySelector('p').innerHTML; //search for the first p tag
console.log(pContent); //test content in p
Using jQuery:
// Attach onclick listener to li items of interest
$("your-li-selector").on('click', function () {
// Select all p tags within the clicked element
var pTags = $('p', this);
// Iterate over all p tags
pTags.each(function () {
// Do search actions with `this.innerHtml` or `$(this).html()`
});
});
$("li").click(function(){
var myPrag=this.innerHTML.find("p");
});
Then use myParag
P.s. not tested

Inserting variable into array item

I have an array of elements from my webpage which I am trying to then insert some html, stored as a variable into a matching array item. For example
<div class="play">
<div>
<p>Item to be inserted after this p tag</p>
</div>
</div>
var elements = $('.play');
//elements length = 4;
var item = '<p>HTML to be inserted</p>'
$(item).appendTo(elements[1]);
In the above code I am trying to insert 'item' into the second value in the array within the child div shown in the html, however I am unsure how to insert it into the child div. At present this inserts 'item' after the parent html tag containing .play.
Any help would be greatly appreciated.
Note that elements isn't an array, it's a jQuery object, which means you can use jQuery methods to traverse through the DOM:
elements.eq(1).find("div").append(item);
Demo: http://jsfiddle.net/rgQ7g/
.eq(1) selects the second item but returns it wrapped in another jQuery object, so then you can use .find("div") to get to the child div and .append() your item to it.
Try after():
$('.play').find('p').after(item);
This inserts content AFTER a selected element in the DOM. It also does it for all the classes named .play
If you need to specify an index, I recommend a function:
function appendPlay(index, content) {
$('.play').eq(index).find('p').after(content);
}
appendPlay(2, '<p>HTML to be inserted</p>');
jsFiddle
please try using
var element = $('.play div p');
var item = '<p>HTML to be inserted</p>'
$(element).parent().append(item);
Edited
from
var element = $('.play div');
var item = '<p>HTML to be inserted</p>'
$(element).append(item);
Well, I guess this would work:
$(item).appendTo($(elements));
But a better solution would be using:
$('.play').find('p').after(item);
You can use link below. (I edited code after comment)
You should write code like;
var selector = ".play",
text = "<p>HTML to be inserted</p>";
$(selector + " div p").eq(1).after(text);
http://jsbin.com/esesul/5/

Categories