How to create the DOM element using jquery [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do I add a DOM element with jQuery?
var re = new RegExp("\\b(" + l + ")\\b")
var sOpen = "<span class='highlight'>";
var sClose = "</span>";
var newhtml = sp.replace(re, sOpen + l + sClose, "gi");
alert(newhtml);
$('.highlight').css('color', 'yellow');
I am getting newHtml value as
I love to work with <span class='highlight'>jquery</span>
I am highlight the highlight class item. jquery but its not hightlighting the text. please can any body tell me is that something I am doing wrong here?
how to create a newhtml as DOm element?
thanks

Even better would be to wrap it with the built-in logic:
$('myelement').wrap('<span/>').parent().addClass('highlight');

You can create an object of it and add it to the DOM:
var newhtml = $(sp.replace(re, sOpen + l + sClose, "gi"));
$(body).append(newhtml);

Related

Write text over div without using .text()

I've got again a rather simple question, that I couldn't find an answer to.
I was using sofar the Jquery function .text() to write text on mouseenter on a dynamically created div. I came to realise that this only worked on my Iceweasel, but not in Chrome for instance. Instead ot .text() everywhere people advised of using the .val(), but I can't seem to figure out exactly how to use it in my implementation, since the divs had no previous text value.
Please find below a simple code, with .text() to understnad the question.
(function(){
for (var i = 0; i < 3; i++) {
var span = document.createElement("span");
span.innerHTML = "<img width=\"" + data.size[i][0] + "\" height=\"" + data.size[i][1] + "\" id=\"" + i + "\">";
span.style.position = "absolute";
span.style.left = data.coords[i][0] + "px";
span.style.top = data.coords[i][1] + "px";
document.body.appendChild(span);
}
}());
for (var i=0; i<3; i++) {
$('#' + i).mouseenter(function() {
$(this).text("text");
});
$('#' + i).mouseleave(function() {
$(this).text("")
});
}
http://jsfiddle.net/ckpx6esj/1/
I hope someone can give me an idea, of how to apply .val() or use something else entirely to make this work for chrome also.
Best Regards and Thanks in advance!
The problem is that you put text in an image tag!
<img>Some text</img>
This is invalid HTML, see this answer.
If you want text over an image, I suggest using a div with background: url(...) instead.
Updated fiddle.
The cleverest I could think to don't screw up your for loop is appending a <p> tag containing your text and removing it on mouseleave:
for (var i=0; i<3; i++){
$('#' + i).on("mouseenter",function() {
$(this).parent().append("<p>text</p>");
});
$('#' + i).on("mouseleave",function() {
$(this).parent().find("p").remove();
});
}
Fiddle:
http://jsfiddle.net/ckpx6esj/2/
Besides, text was not working because you are listening to the image (<img>) instead of the span. Images has no .text() prototype, hence you should access its parent() (which is a <span> in that case) if you want to use the .text() prototype, but using .text() on the parent will remove the image, hence the idea of appending the text and removing it later.
According to specification, val() function is to set value attribute and it only matters for input fields on your page. text() function is to change content of your element.
The .val() method is primarily used to get the values of form elements
such as input, select and textarea.
So you should use text() function in your code.
Also according to your code you change text property of <img> element. This is not good. You should change text of your <span>. So just move your id to span element.
If you want the jQuery equivalent of Javascript's native innerHtml, go for $(this).html('text');.
Take a look at these functions:
http://api.jquery.com/html/
$(this).html('text');
http://api.jquery.com/append/
$(this).append('text'); // Note that this appends instead of replaces
http://api.jquery.com/val/
$(this).val('text');
Or if you're feeling adventurous:
http://api.jquery.com/appendto/
$('text').appendTo($(this)); // Performance penalty for creating an object out of 'text'
First I will use class instead id, it will save using the second loop,
also if you want to have also text and also image you can do it but it will be littel complicated I would recommand add some child element to the span that will contain the text, I didnt do it just for the challenge
http://jsfiddle.net/ckpx6esj/5/
simple plugin to change the text without changing the html elements
$.fn.selectorText = function(text) {
var str = '';
this.contents().each(function() {
if (this.nodeType === 3) {
if(typeof(text) === 'string'){
this.textContent = text;
return false;
}else{
str += this.textContent || this.innerText || '';
}
}
});
return str;
};
var thisData = [{
'coords' : [[100,100], [300, 300], [200, 200]],
'size' : [[30, 30], [30, 30], [30, 30]]
}];
var data = thisData[0];
(function(){
for (var i = 0; i < 3; i ++){
var span = document.createElement("span");
span.setAttribute('class','spanImage');
span.style.position = "absolute";
span.style.left = data.coords[i][0] + "px";
span.style.top = data.coords[i][1] + "px";
span.innerHTML = "\n<img width=\"" + data.size[i][0] + "\" height=\"" + data.size[i][1] + "\" id=\"" + i + "\">";
document.body.appendChild(span);
}
$('.spanImage')
.on( 'mouseenter', function() {
$(this).selectorText('text');
})
.on( 'mouseleave', function() {
$(this).selectorText('');
});
}());

Bind function to dynamically created element [duplicate]

This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
I have some javascript which generates some html elements, like below:
for (var i = 0; i < suggestions.length; i++) {
var suggestion = suggestions[i];
var $li = $('<li data-profile-id="'+ suggestion.id + '" data-profile-name="'+suggestion.first_name + ' ' + suggestion.last_name + ' " class="search-name-result" ></li>');
$suggestionsUl.append($li);
var $img = $('<img src="/img/profile/' + suggestion.picture_url + '" class="search-suggest-img pull-left" />');
$li.append($img);
var $link = $('' + suggestion.first_name + ' ' + suggestion.last_name + '');
$li.append($link);
}
What I need to be able to do is also assign a function to each dynamically created li element, something like the below code:
$('.search-name-result').on('click', function(e){
$input.val($('.search-name-result').data('profile-name'));
});
But im not sure how to assign this to each li when they are created.
Thanks
Almost there, but actually delegate it using a parent container like document
$(document).on('click','.search-name-result', function(e){
$input.val($(this).data('profile-name'));
});
Also, you can change
$('.search-name-result').data('profile-name'))
to use $(this) like
$(this).data('profile-name'))
since it will be the clicked .search-name-result
You should use event delegation for dynamically added elements.
$(document).on('click','.search-name-result', function(e){
$input.val($('.search-name-result').data('profile-name'));
});

Why can't I write to this div using javascript? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 7 years ago.
I have tried several methods of writing to this div, but to know avail:
The 'testing' works, but nothing else:
document.write("testing");
document.getElementById('menu2').innerHTML += "<br>Some new content!";
var node = document.getElementById("menu2");
node.innerHTML = "<p>" + "Hello" + "</p>";
(function printMsg() {
var node = document.getElementById("menu2");
node.innerHTML = "<p>" + "Hello World!" + "</p>";
})();
and in the html
<div id="menu2">x</div>
the x shows
As of this writing, this is at http://www.jchess.nyc (index page)
You problem is that you put script in the begining of the body, so it's executed before div#menu2 is avaialable in DOM.
The simplest fix is to move script tag before closing </body> tag. Also remove document.write, it's not a problem here but you don't need it.
<script>
document.getElementById('menu2').innerHTML += "<br>Some new content!";
var node = document.getElementById("menu2");
node.innerHTML = "<p>" + "Hello" + "</p>";
(function printMsg() {
var node = document.getElementById("menu2");
node.innerHTML = "<p>" + "Hello World!" + "</p>";
})();
</script>
</body>
That happens because document.write just writes the text you specify in body; it's not required for any element to be loaded to be able to document.write, but document.getElementById() searches for the element in DOM, which isn't created immediately when you begin executing your script, so your script is trying to access your element with id menu2 before it is loaded.
To be able to use document.getElementById(), you should wait for the DOM to load, by placing all your methods accessing DOM to:
window.onload=function(){
}

JavaScript RegExp match text ignoring HTML

Is it possible to match "the dog is really really fat" in "The <strong>dog</strong> is really <em>really</em> fat!" and add "<span class="highlight">WHAT WAS MATCHED</span>" around it?
I don't mean this specifically, but generally be able to search text ignoring HTML, keeping it in the end result, and just add the span above around it all?
EDIT:
Considering the HTML tag overlapping problem, would it be possible to match a phrase and just add the span around each of the matched words? The problem here is that I don't want the word "dog" matched when it's not in the searched context, in this case, "the dog is really really fat."
Update:
Here is a working fiddle that does what you want. However, you will need to update the htmlTagRegEx to handle matching on any HTML tag, as this just performs a simple match and will not handle all the cases.
http://jsfiddle.net/briguy37/JyL4J/
Also, below is the code. Basically, it takes out the html elements one by one, then does a replace in the text to add the highlight span around the matched selection, and then pushes back in the html elements one by one. It's ugly, but it's the easiest way I could think of to get it to work...
function highlightInElement(elementId, text){
var elementHtml = document.getElementById(elementId).innerHTML;
var tags = [];
var tagLocations= [];
var htmlTagRegEx = /<{1}\/{0,1}\w+>{1}/;
//Strip the tags from the elementHtml and keep track of them
var htmlTag;
while(htmlTag = elementHtml.match(htmlTagRegEx)){
tagLocations[tagLocations.length] = elementHtml.search(htmlTagRegEx);
tags[tags.length] = htmlTag;
elementHtml = elementHtml.replace(htmlTag, '');
}
//Search for the text in the stripped html
var textLocation = elementHtml.search(text);
if(textLocation){
//Add the highlight
var highlightHTMLStart = '<span class="highlight">';
var highlightHTMLEnd = '</span>';
elementHtml = elementHtml.replace(text, highlightHTMLStart + text + highlightHTMLEnd);
//plug back in the HTML tags
var textEndLocation = textLocation + text.length;
for(i=tagLocations.length-1; i>=0; i--){
var location = tagLocations[i];
if(location > textEndLocation){
location += highlightHTMLStart.length + highlightHTMLEnd.length;
} else if(location > textLocation){
location += highlightHTMLStart.length;
}
elementHtml = elementHtml.substring(0,location) + tags[i] + elementHtml.substring(location);
}
}
//Update the innerHTML of the element
document.getElementById(elementId).innerHTML = elementHtml;
}
Naah... just use the good old RegExp ;)
var htmlString = "The <strong>dog</strong> is really <em>really</em> fat!";
var regexp = /<\/?\w+((\s+\w+(\s*=\s*(?:\".*?"|'.*?'|[^'\">\s]+))?)+\s*|\s*)\/?>/gi;
var result = '<span class="highlight">' + htmlString.replace(regexp, '') + '</span>';
A simpler way with JQuery would be.
originalHtml = $("#div").html();
newHtml = originalHtml.replace(new RegExp(keyword + "(?![^<>]*>)", "g"), function(e){
return "<span class='highlight'>" + e + "</span>";
});
$("#div").html(newHtml);
This works just fine for me.
Here is a working regex example to exclude matches inside html tags as well as javascripts:
http://refiddle.com/lwy6
Use this regex in a replace() script.
/(a)(?!([^<])*?>)(?!<script[^>]*?>)(?![^<]*?<\/script>|$)/gi
this.keywords.forEach(keyword => {
el.innerHTML = el.innerHTML.replace(
RegExp(keyword + '(?![^<>]*>)', 'ig'),
matched => `<span class=highlight>${matched}</span>`
)
})
You can use string replace with this expression </?\w*> and you'll get your string
If you use jQuery, you can use the text property on the element containing the text you're searching for. Given this markup:
<p id="the-text">
The <strong>dog</strong> is really <em>really</em> fat!
</p>
This would yield "The dog is really really fat!":
$('#the-text').text();
You could do your regex search on that text instead of trying to do so in the markup.
Without jQuery, I'm unsure of an easy way to extract and concatenate the text nodes from all child elements.

Adding and removing a division using JavaScript

<script type="text/javascript">
var num=2;
function addElement()
{
var ni = document.getElementById('myDiv');
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = 'Subject-' + num + '* :<input type="text" id=textbox"' + num + '"/><a href=\'#\' onclick=\'removeElement('+divIdName+')\'>Remove</a>';
ni.appendChild(newdiv);
num=num+1;
}
function removeElement(divNum)
{
alert(divNum.id);
var d = document.getElementById('myDiv');
var dd =document.getElementById(divNum.id);
d.removeChild(dd);
for(var i=0;i<d.childNodes.length;i++)
{
if(d.childNodes[i].id==divNum.id)
{
d.removeChild(d.childNodes[i]);
}
}
}
</script>
It is working fine in Internet Explorer but in Firefox it is giving error like the element my1Div is not defined. Why is this happening and how can it be corrected?
Thanks.
Change
newdiv.innerHTML = 'Subject-' + num + '* :<input type="text" id=textbox"' + num + '"/><a href=\'#\' onclick=\'removeElement('+divIdName+')\'>Remove</a>';
to
newdiv.innerHTML = 'Subject-' + num + '* :<input type="text" id=textbox"' + num + '"/><a href=\'#\' onclick=\'removeElement("'+divIdName+'")\'>Remove</a>';
(add the " quotes)
and then change
var dd =document.getElementById(divNum.id);
to
var dd =document.getElementById(divNum);
(remove .id)
Your quotes are wrong in both the removeElement call and the textbox ID. This always happens when kludging HTML together from strings, especially JavaScript inside HTML inside JavaScript strings. That's too many levels of nesting for the mind to cope with. Use DOM methods instead.
Avoid setAttribute, it's less readable than normal DOM Level 1 HTML methods, and has many bugs in IE. removeElement is also a very odd way of saying d.parentNode.removeChild(d) twice — ineffectively, unless you have two elements with the same ID. (Which you shouldn't as it's quite invalid. If you did, it would fail for every other matching child as you are doing a destructive forward iteration.)
If you use a closure you could also lose all the nasty stuff with remembering which element is which, and replace the lot with:
function addElement() {
var newdiv= document.createElement('div');
newdiv.appendChild(document.createTextNode('Subject-' + num + '* :'));
newdiv.appendChild(document.createElement('input'));
newdiv.appendChild(document.createElement('a'));
newdiv.lastChild.href='#';
newdiv.lastChild.onclick= function() {
newdiv.parentNode.removeChild(newdiv);
return false;
};
newdiv.lastChild.appendChild(document.createTextNode('Remove'));
document.getElementById('myDiv').appendChild(newdiv);
}
I haven't ran the code but I guess that you might be hitting DOM TextNodes, which don't have many of the methods that elements have defined. To work around this you can specifically check for text nodes using something like
if (d.childNodes[i].nodeName === "#text") continue;
Of course this might be the totally wrong solution. If you could edit your post and say which line is erroring that might help.

Categories