I'm trying to insert a #HTML.ActionLink element inside a li element using the following code:
var ul = document.getElementById('container');
var enlace = '#Html.ActionLink("Details", "Details", "Elements", new { id = "5" }, null)';
var li = document.createElement('li');
li.appendChild(document.createTextNode('My title'));
li.appendChild(document.createElement('br'));
///////////////////////////////////////////////
li.appendChild(document.createElement(enlace));
///////////////////////////////////////////////
ul.appendChild(li);
Is it possible?
You're passing an entire HTML element to document.createElement(), which expects only a tag name. Essentially, you're doing this:
document.createElement('some text')
whereas the function works like this:
document.createElement('a');
You can probably fix this by separating the creation of the element from the setting of the element's HTML to your custom server-generated HTML. Replacing just the code surrounded by the comments, it might look like this:
///////////////////////////////////////////////
var enlaceElement = document.createElement('a');
enlaceElement.innerHTML = enlace;
li.appendChild(enlaceElement);
///////////////////////////////////////////////
I have a full demo here.
Related
I have a list with people's data inside it has a li element with 3 p tags inside, one for name, one for address and one for email.
I filled this list manually but due to some changes to my code I had to rewrite this so the html would be made with javascript.
My code looked like this
<p class="adres">#logopedist.Adres</p>
<p class="email">#logopedist.Email</p>
<p class="mobiel">#logopedist.Mobiel</p>
I rewrote this to build the html using javascript. This looks something like this.
var li = document.createElement('li');
li.className = "lijst";
li.id = "lijst";
li.onclick = "ficheVullen(this)";
p.className = "naam";
p.innerHTML = objLogos.Naam[i];
li.appendChild(p);
p.className = "adres";
p.innerHTML = objLogos.Adres[i];
li.appendChild(p);
var p = document.createElement('p');
p.className = "mobiel";
p.innerHTML = objLogos.Mobiel[i];
li.appendChild(p);
My list generates properly. But in my old code I had this at the start of the list.
<li class="lijst" onclick="ficheVullen(this)">
Whenever you would click an li element it would fill a div with the info from the p tags inside that li, so it would fill the div with name, address, mobile,etc
I cannot seem to get this function to work anymore. It only works on the very first LI element and only works for the name. Even though my code is the same and I append classes to the tags like it had in my old code.
The function looks like this:
function ficheVullen() {
FicheNaam = document.getElementById("FicheNaam");
FicheAdres = document.getElementById("FicheAdres");
FicheGSM = document.getElementById("FicheGSM");
FicheNaam.innerHTML = this.querySelector('.naam').textContent;
FicheGSM.innerHTML = this.querySelector('.mobiel').textContent;
FicheAdres.innerHTML = this.querySelector('.adres').textContent;
I get this error now. Cannot read property 'textContent' of null
I call this function here:
window.onload = function() {
changePage(1);
document.getElementById("lijst").addEventListener("click", ficheVullen);
};
The changepage function is part of my pagination where I use javascript to build the list.
When I move the eventlistener out of this I get this error: Cannot read property 'addEventListener' of null.
I hope this gives enough context
You have to use setAttribute to set id.
elm.setAttribute("id", "uniqueId");
Your case : li.setAttribute("id", "lijst")
li.id = "lijst"; will add "id" to object not as attribute
const parent = document.getElementById("container")
let elm = document.createElement("p")
elm.setAttribute("id", "pElm")
elm.innerText = "p tag"
parent.append(elm)
document.getElementById("pElm").style.background = "red"
<div id="container"></div>
I'm trying to replace multiple links but only the first one is replaced,
all the other remain the same.
function rep(){
var text = document.querySelector(".link").querySelector("a").href;
var newText = text.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
document.querySelector(".link").querySelector("a").href = newText;
}
Any suggestions?
It's multiple a href links inside .link elements which I'm talking about.
Your mistake is in using querySelector, so document.querySelector(".link").querySelector("a") literally translates to: get me the first a inside the first .link;
Use querySelectorAll; and you can combine the two selectors:
Vanilla JS:
[].forEach.call(document.querySelectorAll('.link a'), function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
Or, since you'll select items more often, a little utility:
function $$(selector, ctx){
return Array.from((ctx && typeof ctx === "object" ? ctx: document).querySelectorAll(selector));
}
$$('.link a').forEach(function(a){
a.href = a.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
})
Or in jQuery:
$('.link a').each(function(){
this.href = this.href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/, 'http://google$2com');
});
This doesn't use JQuery, and I've changed your regular expression to something that made more sense for the example. It also works when you run the snippet.
function rep() {
var anchors = document.querySelectorAll(".link a");
for (var j = 0; j < anchors.length; ++j) {
var anchor = anchors[j];
anchor.href = anchor.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
rep();
a[href]:after {
content: " (" attr(href)")"
}
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
<div class="link">
What kind of link is this?
<br/>
And what kind of link is this?
<br/>
</div>
Edit: Expanded example showing multiple anchor hrefs replaced inside multiple link classed objects.
Edit2: Thomas example is a more advanced example, and is more technically correct in using querySelectorAll(".link a"); it will grab anchors in descendants, not just children. Edited mine to follow suite.
If you intend to only select direct children of link class elements, use ".link>a" instead of ".link a" for the selector.
Try using a foreach loop for every ".link" element. It seems that
every ".link" element have at least 1 anchor inside, maybe just one.
Supposing every .link element has 1 anchor just inside, something like
this should do:
$('.link').each(function(){
// take the A element of the current ".link" element iterated
var anchor = $(this).find('a');
// take the current href attribute of the anchor
var the_anchor_href = anchor.attr('href');
// replace that text and achieve the new href (just copied your part)
var new_href = the_anchor_href.replace(/http:\/\/test(.*)http:\/\/main(.*)com/,'http://google$2com');
// set the new href attribute to the anchor
anchor.attr('href', new_href);
});
I did't test it but it should move you to the way. Consider that we
could resume this in 3 lines.
Cheers
EDIT
I give the last try, looking at your DOM of the updated question and using plain javascript (not tested):
var links = document.getElementsByClassName('link');
var anchors = [];
for (var li in links) {
anchors = li.getElementsByTagName('A');
for(var a in anchors){
a.href = a.href.replace(/http:\/\/test(.*)com/, 'http://google$1com');
}
}
I suggest to read the following post comment for some cooler methods of looping/making stuff foreach item.
How to change the href for a hyperlink using jQuery
I always used jQuery before, but I want to switch the following to native javascript for better performance of the website.
var first = $('ul li:first');
var first = $('ul li:last');
$(last).before(first);
$(first).after(last);
From: http://clubmate.fi/append-and-prepend-elements-with-pure-javascript/
Before (prepend):
var el = document.getElementById('thingy'),
elChild = document.createElement('div');
elChild.innerHTML = 'Content';
// Prepend it
el.insertBefore(elChild, el.firstChild);
After (append):
// Grab an element
var el = document.getElementById('thingy'),
// Make a new div
elChild = document.createElement('div');
// Give the new div some content
elChild.innerHTML = 'Content';
// Jug it into the parent element
el.appendChild(elChild);
To get the first and last li:
var lis = document.getElementById("id-of-ul").getElementsByTagName("li"),
first = lis[0],
last = lis[lis.length -1];
if your ul doesn't have an id, you can always use getElementsByTagName("ul") and figure out its index but I would advise adding an id
I guess you are looking for:
Element.insertAdjacentHTML(position, text);
Where position is:
'beforebegin'.
Before the element itself.
'afterbegin'.
Just inside the element, before its first child.
'beforeend'.
Just inside the element, after its last child.
'afterend'.
After the element itself.
And text is a HTML string.
Doc # MDN
You can use insertBefore():
var node = document.getElementById('id');
node.parentNode.insertBefore('something', node);
Documentation: insertBefore()
There is no insertAfter method. It can be emulated by combining the insertBefore method with nextSibling():
node.parentNode.insertBefore('something', node.nextSibling);
I am trying to learn how to clone an element using classname and append it to the body.
here is what i have done but i am not getting any output. is there anything wrong ?
HTML:
<div class="check">hello</div>
CSS:
.check {
top: 100px;
}
JavaScript:
var elem = document.getElementsByClassName('.check');
var temp = elem[0].clonenode(true);
document.body.append(temp);
JSFiddle Link:
http://jsfiddle.net/hAw53/378/
if not JS, jquery solution is also welcomed.
You were almost there:
var elem = document.getElementsByClassName('check'); // remove the dot from the class name
var temp = elem[0].cloneNode(true); // capitalise "Node"
document.body.appendChild(temp); // change "append" to "appendChild"
<div class="check">hello</div>
You have 3 errors. Correct code:
var elem = document.getElementsByClassName('check'); // check, not .check
var temp = elem[0].cloneNode(true); // cloneNode, not clonenode
document.body.appendChild(temp); // appendChild, not append
Demo: http://jsfiddle.net/hAw53/379/
There are a few issues with your code.
getElementsByClassName() takes a class name (check), not a selector (.check)
cloneNode() is spelled with a capital N (not clonenode())
appendChild() is the name of the DOM method for appending a child (not append())
Correct version:
var elem = document.getElementsByClassName('check');
var temp = elem[0].cloneNode(true);
document.body.appendChild(temp);
You can do:
$('.check').clone().appendTo('body');
You're code had errors. First you used class selector and not the class name. Then you used an undefined property(properties are case sensitive) and you've to use appendChild instead of append which is a part of jQuery. You're too much confused with native javascript and jQuery.
in Jquery it's very simple, you just need to define inside what the new element apears.
var elem = $('.check');
elem.clone().prependTo( "body");
I have an xml document (from a feed), which I'm extracting values from:
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = $(this).find("description").text();
Now inside "description" i need to get the img element, but this is causing me some problems. "descripttion" is a regular string element and it seems i can't call the ".find()" method on this, so what do i do?
I have tried calling .find():
var img = $(this).find("description").find("img");
But it's a no go. The img is wrapped in a span, but I can't get to this either. Any suggestions? I'd prefer to avoid substrings and regex solutions, but I'm at a loss.
I've also tried turning the "description" string into an xml object like so:
var parser = new DOMParser();
var desc = parser.parseFromString(test,'text/xml');
$(desc).find("img").each(function() {
alert("something here");
});
But that doesn't work either. It seems like it would, but I get a "document not well formed" error.
Try enclosing the contents of the description tag in a dummy div, that seemed to work better for me, and allowed jQuery's .find() to work as expected.
e.g.
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = '<div>' + $(this).find("description").text() + '</div>';
var image = $(description).find('img');
Hi and thanks for the prompt replies. I gave GregL the tick, as I'm sure his solution would have worked, as the principle is the same as what I ended up with. My solution looks like this:
$(feed_data).find("item").each(function() {
if(count < 3) {
//Pull attributes out of the current item. $(this) is the current item.
var title = $(this).find("title").text();
var link = $(this).find("link").text();
var description = $(this).find("description").text();
var thumbnail = "";
var temp_container = $("<div></div>");
temp_container.html(description);
thumbnail = temp_container.find("img:first").attr("src");
So wrap the string in a div, and then use "find()" to get the first img element. I now have the image source, which can be used as needed.
maybe you should try to convert the description text to html tag and then try to traverse it via jquery
$('<div/>').html($(this).find("description").text()).find('img')
note: not tested