Dojo equivalent to jQuery.text function? - javascript

What is the Dojo equivalent to $("...").text("asdf") and $("...").text()?
Also is there a wiki or site that provides dojo equivalents of jQuery functions?

A similar function in dojo is NodeList.text()
http://dojotoolkit.org/reference-guide/1.7/dojo/NodeList-manipulate.html#text
You can use like below.
dojo.query("#id").text("asdf");
var txt = dojo.query("#id").text();

You are looking for the dojo/dom-prop module. If you look at the source, there is special handling for the textContent property if the current browser does not support it.
if(propName == "textContent" && !has("dom-textContent")) {
ctr.empty(node);
node.appendChild(node.ownerDocument.createTextNode(value));
return node;
}
Your code would look like the following:
domProp.set(node, "textContent", "hello world!");
or
domProp.get(node, "textContent");

Just append a node to the element:
someElement.appendChild(document.createTextNode('asdf'));
You also might need to clear it beforehand:
while(someElement.firstChild) someElement.removeChild(someElement.firstChild);
As for getting the text, I don't know if there's a direct equivalent but you probably won't need one. Just read the nodeValue of the element's firstChild.

Use can do this as
dojo.query('#yourdiv')[0].lastChild.textContent = 'text';
var text = dojo.query('#yourdiv')[0].lastChild.textContent

Related

How to fill this textbox? [duplicate]

I need to set the text within a DIV element dynamically. What is the best, browser safe approach? I have prototypejs and scriptaculous available.
<div id="panel">
<div id="field_name">TEXT GOES HERE</div>
</div>
Here's what the function will look like:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById('field_name');
//Make replacement here
}
You can simply use:
fieldNameElement.innerHTML = "My new text!";
Updated for everyone reading this in 2013 and later:
This answer has a lot of SEO, but all the answers are severely out of date and depend on libraries to do things that all current browsers do out of the box.
To replace text inside a div element, use Node.textContent, which is provided in all current browsers.
fieldNameElement.textContent = "New text";
function showPanel(fieldName) {
var fieldNameElement = document.getElementById("field_name");
while(fieldNameElement.childNodes.length >= 1) {
fieldNameElement.removeChild(fieldNameElement.firstChild);
}
fieldNameElement.appendChild(fieldNameElement.ownerDocument.createTextNode(fieldName));
}
The advantages of doing it this way:
It only uses the DOM, so the technique is portable to other languages, and doesn't rely on the non-standard innerHTML
fieldName might contain HTML, which could be an attempted XSS attack. If we know it's just text, we should be creating a text node, instead of having the browser parse it for HTML
If I were going to use a javascript library, I'd use jQuery, and do this:
$("div#field_name").text(fieldName);
Note that #AnthonyWJones' comment is correct: "field_name" isn't a particularly descriptive id or variable name.
I would use Prototype's update method which supports plain text, an HTML snippet or any JavaScript object that defines a toString method.
$("field_name").update("New text");
Element.update documentation
$('field_name').innerHTML = 'Your text.';
One of the nifty features of Prototype is that $('field_name') does the same thing as document.getElementById('field_name'). Use it! :-)
John Topley's answer using Prototype's update function is another good solution.
The quick answer is to use innerHTML (or prototype's update method which pretty much the same thing). The problem with innerHTML is you need to escape the content being assigned. Depending on your targets you will need to do that with other code OR
in IE:-
document.getElementById("field_name").innerText = newText;
in FF:-
document.getElementById("field_name").textContent = newText;
(Actually of FF have the following present in by code)
HTMLElement.prototype.__defineGetter__("innerText", function () { return this.textContent; })
HTMLElement.prototype.__defineSetter__("innerText", function (inputText) { this.textContent = inputText; })
Now I can just use innerText if you need widest possible browser support then this is not a complete solution but neither is using innerHTML in the raw.
If you really want us to just continue where you left off, you could do:
if (fieldNameElement)
fieldNameElement.innerHTML = 'some HTML';
nodeValue is also a standard DOM property you can use:
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
if(fieldNameElement.firstChild)
fieldNameElement.firstChild.nodeValue = "New Text";
}
el.innerHTML='';
el.appendChild(document.createTextNode("yo"));
If you're inclined to start using a lot of JavaScript on your site, jQuery makes playing with the DOM extremely simple.
http://docs.jquery.com/Manipulation
Makes it as simple as:
$("#field-name").text("Some new text.");
Use innerText if you can't assume structure
- Use Text#data to update existing text
Performance Test
function showPanel(fieldName) {
var fieldNameElement = document.getElementById(field_name);
fieldNameElement.removeChild(fieldNameElement.firstChild);
var newText = document.createTextNode("New Text");
fieldNameElement.appendChild(newText);
}
Here's an easy jQuery way:
var el = $('#yourid .yourclass');
el.html(el.html().replace(/Old Text/ig, "New Text"));
In HTML put this
<div id="field_name">TEXT GOES HERE</div>
In Javascript put this
var fieldNameElement = document.getElementById('field_name');
if (fieldNameElement)
{fieldNameElement.innerHTML = 'some HTML';}

Regex for visible text, not HTML

If i had a string:
hey user, what are you doing?
How, with regex could I say: look for user, but not inside of < or > characters? So the match would grab the user between the <a></a> but not the one inside of the href
I'd like this to work for any tag, so it wont matter what tags.
== Update ==
Why i can't use .text() or innerText is because this is being used to highlight results much like the native cmd/ctrl+f functionality in browsers and I dont want to lose formatting. For example, if i search for strong here:
Some <strong>strong</strong> text.
If i use .text() itll return "Some strong text" and then I'll wrap strong with a <span> which has a class for styling, but now when I go back and try to insert this into the DOM it'll be missing the <strong> tags.
If you plan to replace the HTML using html() again then you will loose all event handlers that might be bound to inner elements and their data (as I said in my comment).
Whenever you set the content of an element as HTML string, you are creating new elements.
It might be better to recursively apply this function to every text node only. Something like:
$.fn.highlight = function(word) {
var pattern = new RegExp(word, 'g'),
repl = '<span class="high">' + word + '</span>';
this.each(function() {
$(this).contents().each(function() {
if(this.nodeType === 3 && pattern.test(this.nodeValue)) {
$(this).replaceWith(this.nodeValue.replace(pattern, repl));
}
else if(!$(this).hasClass('high')) {
$(this).highlight(word);
}
});
});
return this;
};
DEMO
It could very well be that this is not very efficient though.
To emulate Ctrl-F (which I assume is what you're doing), you can use window.find for Firefox, Chrome, and Safari and TextRange.findText for IE.
You should use a feature detect to choose which method you use:
function highlightText(str) {
if (window.find)
window.find(str);
else if (window.TextRange && window.TextRange.prototype.findText) {
var bodyRange = document.body.createTextRange();
bodyRange.findText(str);
bodyRange.select();
}
}
Then, after you the text is selected, you can style the selection with CSS using the ::selection selector.
Edit: To search within a certain DOM object, you could use a roundabout method: use window.find and see whether the selection is in a certain element. (Perhaps say s = window.getSelection().anchorNode and compare s.parentNode == obj, s.parentNode.parentNode == obj, etc.). If it's not in the correct element, repeat the process. IE is a lot easier: instead of document.body.createTextRange(), you can use obj.createTextRange().
$("body > *").each(function (index, element) {
var parts = $(element).text().split("needle");
if (parts.length > 1)
$(element).html(parts.join('<span class="highlight">needle</span>'));
});
jsbin demo
at this point it's evolving to be more and more like Felix's, so I think he's got the winner
original:
If you're doing this in javascript, you already have a handy parsed version of the web page in the DOM.
// gives "user"
alert(document.getElementById('user').innerHTML);
or with jQuery you can do lots of nice shortcuts:
alert($('#user').html()); // same as above
$("a").each(function (index, element) {
alert(element.innerHTML); // shows label text of every link in page
});
I like regexes, but because tags can be nested, you will have to use a parser. I recommend http://simplehtmldom.sourceforge.net/ it is really powerful and easy to use. If you have wellformed xhtml you can also use SimpleXML from php.
edit: Didn't see the javascript tag.
Try this:
/[(<.+>)(^<)]*user[(^>)(<.*>)]/
It means:
Before the keyword, you can have as many <...> or non-<.
Samewise after it.
EDIT:
The correct one would be:
/((<.+>)|(^<))*user((^>)|(<.*>))*/
Here is what works, I tried it on your JS Bin:
var s = 'hey user, what are you doing?';
s = s.replace(/(<[^>]*)user([^<]>)/g,'$1NEVER_WRITE_THAT_ANYWHERE_ELSE$2');
s = s.replace(/user/g,'Mr Smith');
s = s.replace(/NEVER_WRITE_THAT_ANYWHERE_ELSE/g,'user');
document.body.innerHTML = s;
It may be a tiny little bit complicated, but it works!
Explanation:
You replace "user" that is in the tag (which is easy to find) with a random string of your choice that you must never use again... ever. A good use would be to replace it with its hashcode (md5, sha-1, ...)
Replace every remaining occurence of "user" with the text you want.
Replace back your unique string with "user".
this code will strip all tags from sting
var s = 'hey user, what are you doing?';
s = s.replace(/<[^<>]+>/g,'');

What does $$('foo') mean in JavaScript source code?

I have the following in javascript:
var entriesString = '';
$$('select[id=shopId]').each(function(elem, i){
shops[i] = elem.value;
entries[i] = new Array();
$$('input[id=entry'+i+']').each(function(elem, c){
if(elem.value != '') entries[i][c] = elem.value.replace(".", "").replace(",", "."); else entries[i][c] = '0.0'
});
entriesString += '&entry'+i+'=' + entries[i];
});
Now I'm new to JS and therefore do not know what the first $$('select[id=shopId]') part means.
It must be some sort of array or collection, due to the .each part it is followed by.
In that loop is again a nested loop that uses the loop variable i in its head.
But again, I don't know what exactly does %%('input[...]') mean. What kind of syntax is this?
Also, where does the data.
This is what entryString looks like for example:
&entry0=65.8,75.5,72.9,67.9,51.1,8.2,47.9&entry1=55.9,33.5,33.8,35.2,26.8,7.0,25.8
Thanks a lot or your help!
That looks like the $$ method of the Prototype library. The documentation is here:
http://www.prototypejs.org/api/utility#method-$$
It selects DOM elements given a CSS-style selector.
$$() is not something of javascript. It seems to be likely that you're using the Prototype Javascript Framework. Here you find the documentation of $$: http://api.prototypejs.org/language/dollardollar/
You are using the Prototype library.
See http://www.prototypejs.org/api/utility/dollar-dollar
your code uses the prototype JS framework. $$('ELEMENTNAME') instanciates all DOM element with ELEMENTNAME (so i.e. all input fields) and returns them as array of objects.
with id==xy it returns that one with id xy
<input type="blah" id="xy" value="123" />
will be found
It use a great function to get elements with css selectors.

Why can't I set value to display in a div?

So I'm new to JavaScript and I'm trying to figure out why doesn't this work:
My function has this line:
document.getElementById("displayResult").value = ("test");
and this is my div:
<div id="displayResult"></div>
div's don't have a value property. You want to set the .innerText property.
And by all means, have fun testing things yourself, but you'll find it a lot easier if you use a framework to do these things (like jQuery)
You will want to use - .innerHTML no?
document.getElementById("displayResult").innerHTML = "<b>test</b>";
.value is only a valid attribute on form fields. You likely want to use the following code:
document.getElementById("displayResult").innerHTML = "test";
you have to test if innerHTML is supported by your brwser. As it is not the DOM Standard.
You can write it like
var oDiv = document.getElementById("displayResult")
if(typeof oDiv.innerHTML != undefined) {
oDiv .innerHTML = message;
} else {
oDiv .appendChild(document.createTextNode(message));
}

Can I get a jQuery object from an existing element

I have a function
function toggleSelectCancels(e) {
var checkBox = e.target;
var cancelThis = checkBox.checked;
var tableRow = checkBox.parentNode.parentNode;
}
how can I get a jQuery object that contains tableRow
Normally I would go $("#" + tableRow.id), the problem here is the id for tableRow is something like this "x:1280880471.17:adr:2:key:[95]:tag:". It is autogenerated by an infragistics control. jQuery doesn't seem to getElementById when the id is like this. the standard dom document.getElementById("x:1280880471.17:adr:2:key:[95]:tag:") does however return the correct row element.
Anyways, is there a way to get a jQuery object from a dom element?
Thanks,
~ck in San Diego
Absolutely,
$(tableRow)
http://docs.jquery.com/Core/jQuery#elements
jQuery can take the DOM elements, try with:
$(tableRow)
or
$(checkBox.parentNode.parentNode)
You should be able to pass the element straight in, like this:
$(tableRow)...
I have tested this by creating a reference to a div, then passing it straight into jQuery and it creates the jQuery object for you.
You can call the jQuery function on DOM elements: $(tableRow)
You can also use the closest method of jQuery in this case:
var tableRowJquery = $(checkBox).closest('tr');
If you want to keep using your ID, kgiannakakis (below), provided an excellent link on how to escape characters with special meaning in a jQuery selector.
See this for how you should escape the id.
try:
var r = $(document.getElementById("XXXX----ID Of Your Row----XXXX"));
now, if document.getElementById doesn't return undefined you can use r as any regular jquery object.

Categories