How to use multiple .find() after selector in jquery chaining? - javascript

Basically what the title says - I'm wondering if there's a way to use .find() on the same jQuery selector multiple times. Or maybe using .find() more than once isn't the right way to do this?
Here's what I'm trying to accomplish:
HTML
<div id="foo">
<h2>A Header</h2>
<p>Some text</p>
</div>
JS
$("#foo").find("h2").html("New header");
$("#foo").find("p").html("New text");
Webstorm complains about the duplicated jQuery selector. Is there a different/better way to do this?

You can use next():
$("#foo").find("h2").html("New header")
.next("p").html("New Text");

To go back to a previous collection in chaining, we can use end()
$("#foo")
.find("h2")
.html("New header")
.end()
.find("p")
.html("New text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<h2>A Header</h2>
<p>Some text</p>
</div>

Use .addBack() to back to first selector after using .find() in chaining.
$("#foo").find("h2").html("New header").addBack().find("p").html("New text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<h2>A Header</h2>
<p>Some text</p>
</div>

The "right way" (the simplest way at least) is to use basic CSS selector syntax:
$("#foo h2").html("New header");
$("#foo p").html("New text");
Or more specifically, this:
$("#foo>h2").html("New header");
$("#foo>p").html("New text");
The first example targets any h2 that is a descendant of foo at any level, whereas the second targets any h2 that is an immediate descendant.
As for trying to do something like this:
x = $("#foo").find("h2").find("p");
This is equivalent to this:
x = $("#foo h2 p");
(You can verify this by going into debug after executing the statement and looking at x.selector.) Which means that you are looking for a paragraph inside a header inside foo:
<div id="foo">
<h2>A Header
<p>**Selector would find this**</p>
</h2>
</div>
And there isn't any such in your example.

<div id="foo">
<h2>A Header</h2>
<p>Some text</p>
</div>
var $foo = $("#foo");
$foo.find("h2").html("New header");
$foo.find("p").html("New text");
OR, if it's possible:
<div id="foo">
<h2>A Header</h2>
<p>Some text</p>
</div>
var htmlString = '<h2>New header</h2><p>New text</p>';
$("#foo").html( htmlString );

It says duplicated jQuery selector because you should ( when possible ) always cache your jQuery selectors, because it's wasteful calling $("#foo") each time you need that object.
So, your code should become like this
HTML
<div id="foo">
<h2>A Header</h2>
<p>Some text</p>
</div>
JS
var foo = $("#foo");
foo.find("h2").html("New header");
foo.find("p").html("New text");

Related

How to replace a link text using JavaScript

I have an HTML code and I want to replace something by JavaScript.
<div class="maindiv">
<div class="childdiv">
Old Text
</div>
</div>
Now I want to change "Old Text" to another like "New Text".
Please let me know if it is possible.
You have to locate your element element inside the DOM , it would be better to use class or/and id propreties.
But in case if you are not allowed to edit the DOM you have to find a way to find the required element like crossing parents that do have an id or a class.
Get first element with this class childdiv.
Get first a tag inside the above found element .
Set innerHTML for the found element to the required value exp: New Text.
Javascript (as you asked for)
<div class="maindiv">
<div class="childdiv">
Old Text
</div>
</div>
<script>
document.getElementsByClassName("childdiv")[0].getElementsByTagName('a')[0].innerHTML="New Text";
</script>
Jquery (same logic as above)
$(document).ready(function(){
$(".childdiv a").text("New Text");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="maindiv">
<div class="childdiv">
Old Text
</div>
</div>
You simply use document.getElementById("my-link").innerHTML = "New Text", but you should put an id attribute to your <a> tag like so:
<a id="my-link" href="www.abc.com" rel="prev">
^^^^^^^^^^^^
Or, if you don't want to edit anything on your original HTML (bad practice):
document.getElementsByTagName("a")[0].innerHTML = "New Text";
You can access such DOM object by using
document.getElementsByClassName("childdiv")[0].childNodes[1].textContent="Updated Text";
I don't really understand your issue but I have tried this and it's working...
<div class="maindiv">
<div class="childdiv">
Old Text
</div>
</div>
and jQuery
$(".link").click(function(e){
e.preventDefault();
$(this).text("New Text");
});
https://jsfiddle.net/294m3my6/
If you want JavaScript
<div class="maindiv">
<div class="childdiv">
Old Text
</div>
</div>
And JS
function Action(evt) {
evt.preventDefault();
document.getElementById("link").innerHTML = "Next Text";
}
document.getElementById('link').addEventListener(
'click', Action, false
);
https://jsfiddle.net/ep3v5u0k/
#Amani has solve my problem. It is what I wanted.
<div class="maindiv">
<div class="childdiv">
Old Text
</div>
</div>
<script>
document.getElementsByClassName("childdiv")[0].getElementsByTagName('a') [0].innerHTML="New Text";
Thanks you so much all of you specially Amani.

Convert innerHTML to text and put into textarea not working

I want to take inner HTML (both tags and text) of an element and put it in textarea, but somehow it is not working. How can I make it work and why is this not working?
HTML:
<div id="element">
<p>Some text</p>
<p>Some text</p>
</div>
<button>Click Me</button>
JS:
$("button").click(function(){
$("#element").html("<textarea>"+$("#element").text($("#element").html())+"</textarea>");
});
DEMO
$("#element").text($("#element").html())
there's your problem
it should be
$("#element").text()
JSFiddle
edit:
updated fiddle

How to change text in div without affecting child elements

I need to modify the following HTML using Javascript,
<div id="1">
some text
<div id="2"></div>
</div>
I have tried using $('#1').text('new text'); However, this unintentionally removes <div id="2">
How should I change some text, without changing the surrounding elements?
This will change the value of the first node (which is a text node in your example):
$('#1').contents()[0].nodeValue = 'new text';
JSFiddle
Try the following
<div id="1">
<span id='myspan'>some text</span>
<div id="2"></div>
</div>
Then use;
$('#myspan').text('new text');
By the way it is a bad practice to use ids with numbers as elements.
You can add a span if you don't want to change the style of your element.
So in your case you will do something like this (I removed the numbers as ids):
<!-- HTML -->
<div id="text-container">
<span id="some-text">some text</span>
<div id="something-else"></div>
</div>
And in your JavaScript:
//JavaScript
$('#some-text').text('new text');
If plausible, do something like the following:
<div id="1">
<span id="edit">some text</span>
<div id="2"></div>
</div>
Then, you can edit your text like so:
$('#edit').text('new text');
Basically, your putting the text you want to edit in its own element with an ID. Keep in mind that you can use any type of element you want, you don't have to use span specifically. You can change this to div or p and you'll still achieve the same result.
the best solution is to check the node type as Node.TEXT_NODE and nodeValue is not null:
$('#1')
.contents()
.filter(function() {
return this.nodeType === Node.TEXT_NODE && this.nodeValue && this.nodeValue.trim();
})
.replaceWith("new text");
My solution as an alternative to others:
var text_to_keep = $('#2').text();
$('#1').text('new text').append('<div id="2">' + text_to_keep + '</div>');
http://jsfiddle.net/LM63t/
P.S. I don't think id's that begin with a number are valid.

Selecting specific contenteditable divs with jQuery

Given the following html for a type of blog post editor:
<div class="entry">
<div class="title" contenteditable="true">
<h2>Title goes here</h2>
</div>
<div class="content" contenteditable="true">
<p>content goes here</p>
</div>
</div>
I'm trying to use jquery to select the .title and .content divs to attach unique event handlers to each.
$('[contenteditable]').on(...);
works for both but
$('[contenteditable] .title').on(...);
or
$('.title').attr('contenteditable', 'true').on(...);
both don't work to select the specific contenteditable block.
You could use the attribute selector in CSS .title[contenteditable="true"].
jsFiddle example
.title[contenteditable="true"] {
background: red;
}
In jQuery: $('.title[contenteditable]').css("background","red")
jsFiddle example
For the first example you have to remove the space between the attribute selector and the class selector, as a space implies descendance.
$('[contenteditable].title').on("click", function(){
$(this).css('color', 'orange');
});
Example: http://jsfiddle.net/2Bsk4/

mootools replace the content of a div

i have the following HTML code
<div id="myDiv">
<p>content</p>
</div>
and the following JS code:
$('myDiv').set('html',htmlCode);
the problem is that the variable htmlCode is something like:
<div id="myDiv"><p>another content</p></div>
so, the result when i run the JS code is something like:
<div id="myDiv">
<div id="myDiv">
<p>another content</p>
</div>
</div>
is there a way to use "set" so that it overrides the entire div? or another solution to get something like:
<div id="myDiv">
<p>another content</p>
</div>
as the result from the JS script?
i know i could just change the variable htmlCode... i just was wondering if there's another solution to this.
Mootools offers a simple replaces method!
//new tmp element that contains the new div
var tmpDiv = new Element('div',{html:'<div id="myDiv"><p>another content</p></div>'});
//new div (first child of my tmp div) replaces the old 'myDiv' (that can be grabbed from the DOM by $)
tmpDiv.getFirst().replaces($('myDiv'));
String.implement({
replaces: function(toReplace) {
Elements.from(this).inject(toReplace, 'after');
toReplace.destroy();
}
});
'<div id="a"><p>ipsum</p></div>'.replaces($('a'));
This should do. Example: http://jsfiddle.net/UvuwG/
$('myDiv').empty();
$('myDiv').adopt(Elements.from(htmlCode).getElement('p'));
You can do
$("myDiv").getParent().set("html", htmlCode);

Categories

Resources