Another jquery dynamic selector - javascript

I just asked a question here about selecting all id's of the form id_* where * is any string and id is the id of the element. I got a great working solution:
$("*[id^=" + id + "_]").each(function() {... // id is the element name
I need to take this one step further now:
All of my ids will be of the form: a_b_c ... where a b and c are arbitrarity strings (that do NOT contain a ''). So, now rather than selecting all the elems of the form id_* where * could be a_b_c ... I need only to select 1 level deep: i.e. all elems of the form id_a. So in other words it stops at the next ''. Is this possible?
As an example:
If my id is: first
And there exist id's: first_second, first_second_third
It will select only first_second

Sounds like you are storing too many values in the id of the field. With HTML5 we now have data- attributes.
Perhaps, you should be making use of data- attributes something like this to link them?
<div id="a">
</div>
<div id="b0" data-parentId='a'>
</div>
<div id="b1" data-parentId='a'>
</div>
<div id="b2" data-parentId='a'>
</div>
<div id="c" data-parentId='b1'>
</div>
It will still validate, as any non-standard attribute starting with data- will be considered valid.
See: http://ejohn.org/blog/html-5-data-attributes/
Your jQuery selectors can then make use of this new attribute, rather than trying to parse strings
Something like this would select all of a's children
var childrenOfA = $("div[data-parentId='a']);

What I ended up doing (and I'm open to faster implementations) is:
$("*[id^=" + id + "_]").each(function() {
//here I simply split the id and test the size of the array
//if its too large (i.e. too deep in the tree), I return true (to continue
// to the next iteration):
var row = $(this);
var split = row.attr('id').split("_");
if(split.length > SOME_PREDETERMINED_VAL)
return true;
//code here
});
I am not totally happy with this since it still traverses all elements (or would it do this anyway regardless of the filter in the each() function??).

This doesn't give you the whole solution, but you could try the attribute prefix selector or the attribute starts with selector
That will allow you to select any descendant of an element:
$("[id^='a_b_']").each(....
Will think how to remove the grandchildren etc, but this might get you started.
EDIT
I have just found that a similar question was asked about jQuery wildcards - this looks as if it will do what you need.

It seems like you are seriously overcomplicating this task. Let's say your structure is currently like this:
<div id="a">
<div id="a_b">
<div id="a_b_c">
</div>
</div>
</div>
Why don't you just do something along these lines...
<div id="a">
<div class="b">
<div class="c">
</div>
</div>
</div>
So, if I JUST wanted #a .b I would do:
$("#a .b").not("#a .c").show();
Makes it a bit more semantic and readable as well. Am I understanding what you're trying to do? Might need to shed a bit more light on what exactly you're doing

The obvious solution is changing your document, for example instead of
<div id="a"></div>
<div id="a_b"></div>
<div id="a_b_c"></div>
you could write
<div id="a" class="l1"></div>
<div id="a_b" class="l2"></div>
<div id="a_b_c" class="l3"></div>
and then select $('.l2[id^=a_]'). If that is not an option, you could try some sort of sieve scheme:
var set = $('[id^='+id+'_]'), i = 0;
while (i < set.length) {
var e = set.eq(i);
if (e.attr('id').substr(id.length+1).match('_')) {
set = set.not(e);
} else {
i++;
}
set = set.not($('[id^='+e.attr('id')+'_]'));
}
(I haven't tested, so there might be errors, and I'm not sure not is the one that subtracts from a result set, but you get the idea.)
It depends on the document structure and browser whether this will be actually faster than the naive implmentation of simply walking through the while set and skipping everything with two _ in the id. (High number of branches per node helps, and it will be probably faster on browsers which have a native implementation of the CSS3 prefix selector which jQuery can call on.)
update: fixed some mistakes. The logic might change depending on your structure, e.g. the innermost if branch is unnecessery if foo_bar always precedes foo_bar_baz.

Related

JavaScript - Select all elements with [data-some] attribute not having a specific value

My Project uses plain JavaScript. I want to select elements which are not having a data-some attribute's value as 'abcd'.
I tried the following.
:not([data-some="abcd"])
this selector returns only elements not having [data-some]. But I want to select only elements not having data-some's attribute as 'abcd'. It can have [data-some="gtf"].
Any help is highly appreciated.
NOTE: I have pasted only the selectors as I need only them. Most stackoverflow questions have answer for selecting elements without a specific data attribute.
You can use a single, though fairly complex, selector:
[data-some]:not([data-some="abcd"])
Be careful with compatibility, you may need a simpler selector plus some script depending on the hosts you need to support.
E.g.
[data-some]:not([data-some="abcd"]) {
background-color: #ffff66;
}
<p data-some="abcd">data-some="abcd"</p>
<p data-some="zzz">data-some="zzz"</p>
<p data-some="">data-some=""</p>
<p>no data-some attribute</p>
var test = document.querySelectorAll(':not([data-some="abcd"])');
for (var i in test) if (test.hasOwnProperty(i)) {
(test[i].style.background = "#DCDCDC");
}
p, h1{
background: #ff7f7f;
}
<div >
<h1 data-some="abcd">hello</h1>
<p data-some="abcd">hello</p>
<p data-some="gtf">hello</p>
</div>
This solution is possible, if you can use Array.prototype.filter:
const elements = document.querySelectorAll("[data-some]");
const result = Array.from(elements).filter(el => el.dataset.some !== "abcd");
console.log(result);
<div data-some="abcd"></div>
<div data-some="gtf"></div>
<div data-some="ooo"></div>
It grabs every element with data-some attribute, creates an array of elements, and filter out these that don't meet condition el.dataset.some !== "abcd".
Get all elements that have the attribute data-some except those with the value "abcd"
$("div[data-some]").not("div[data-some!='abcd']");
https://jsfiddle.net/xz5et4tr/

Can't change class when using getElementsByClass

I've been going around in circles on this one. I have a PHP output that generates a series of DIV elements, and each has a class of L1, L2, L3, etc. These classes have a CSS that's basically blank so they display by default.
The problem is trying to change the class of each DIV to hide it, based on a simple onclick function. I'm using document.getElementsByClass to get (for example) just the DIV CLASS="L1" elements. But when I try to change the class, either with setAttribute('class', 'L1hide') or with className = "L1hide", nothing happens.
I know the HTML/CSS portion works, since I altered the PHP to generate "L1hide" instead of just "L1" and saw that the DIV CLASS="L1hide" elements were indeed hidden.
Is it because I'm trying to both grab the class and change the class at the same time? All the examples I see use getElementById, but this isn't practical for me since ID must be unique. I have zero, one, or more L1/L2/etc. class elements.
Here are some HTML code output by PHP:
<div class="L1"><h3>Owner</h3>
<table>
<tr><td>Jim Smith</td></tr>
</table>
</div>
<div class="L1"><h3>Executives</h3>
<table>
<tr><td>Harry Atkins</td></tr>
<tr><td>Galen Singh</td></tr>
</table>
</div>
<div class="L2"><h3>Managers</h3>
<table>
<tr><td>Andy Jones</td></tr>
<tr><td>Mary Thompson</td></tr>
<tr><td>Bill Murphy</td></tr>
</table>
</div>
And here is some javascript. This should change the image and hide the L1's. The image change DOES work (first 4 lines), but the style won't change (last 2 lines) despite my burnt offerings:
managmentImage.onclick = function() {
if (managmentLevel == "TOP1.png") {
document.getElementById("managementImage").setAttribute("src", "TOP0.png");
managmentLevel = "TOP0.png";
document.getElementsByClassName("L1").className = "L1hide";
divL1 = "L1hide";
} else { ...
Note: There is basically duplicate "else" code to change the image back, and to re-display the L1's. I only provided the first half of the "if" statement since the solution would also apply to the remaining "else" portion.
getElementsByClass is returning an array-like collection of nodes; those don't have className, individual nodes do.
You can't iterate it normally, because it is a live collection: if you change the class of the first element, the array shortens by one, so you will only process half of the nodes if you iterate from start to end. Iterating from end to start fixes this issue.
var elements = document.getElementsByClassName("L1");
console.log(elements);
var i = elements.length;
while (i--) {
elements[i].className = "L1hide";
}
.L1hide {
display: none;
}
<div class="L1"><h3>Owner</h3>
<table>
<tr><td>Jim Smith</td></tr>
</table>
</div>
<div class="L1"><h3>Executives</h3>
<table>
<tr><td>Harry Atkins</td></tr>
<tr><td>Galen Singh</td></tr>
</table>
</div>
<div class="L2"><h3>Managers</h3>
<table>
<tr><td>Andy Jones</td></tr>
<tr><td>Mary Thompson</td></tr>
<tr><td>Bill Murphy</td></tr>
</table>
</div>
getElementByClassName() returns an array.
You must iterate on it and then change the property.

JSF Set CSS Style Using Javascript?

I have been looking with no success to see if I can dynamically apply a css style to JSF component or div using javascript. Is this possible.
This is pseudo code
<div style="myJSStyleFunction("#{myBean.value}")"> stuff </div>
And the function would return something like "position:relative;left:25px;"
I've had no luck and maybe it can't be done but would like a second opinion.
Edit:
I'm trying to see if I can keep a separation / reduce the coupling between the presentation/view and the model/controller. This is for indenting commenting or product reviews (to nest replies to comments or reviews). The most I really want to track is an integer on how deep a reply is. First level = 0 second level = 1, and so on. So a comment or product review would be 0 deep, a reply to the comment or review would be 1 and so on.
Then in the EL I wanted to call a javascript function and do something like
<script>
myJSStyleFunction(depth){
if(depth<=5){
var nest=20*depth;
var style="position:relative;left:" + nest + "px;";
return style;
}
}
</script>
And then then say for a third level comment (a reply to a reply) it would look like this:
<div style="position:relative;left:40px;"> stuff </div>
where
#{myBean.value}
evaluates to 2
I suspect like Daniel says I'll have to tightly couple the view but I'd rather not have to. I'd think there has to be a way. But maybe not.
I don't know where there are cleaner solutions for this. However this is one suggestion.
Assume your page looks like below and myBean.getValue() method returns an integer.
<h:form id="frm">
<div style="#{myBean.value}"> div1 </div>
<div style="#{myBean.value}"> div2 </div>
</h:form>
So you can do something like this at 'window.onload'.
<head>
<script>
window.onload = function() {
var childList = document.forms['frm'].childNodes;
for(var i = 0; i < childList.length; i++) {
if(childList[i].nodeName == 'DIV') {
var _div = childList[i];
var depth = _div.getAttribute('style');
_div.setAttribute('style', 'position:relative;left:' +(depth *20)+ 'px;');
}
}
}
</script>
</head>
Note: 1. In above sample code I assume all the DIVs inside the form should be indented.
2. For IE you may need to use _div.style.setAttribute('cssText','position:relative;left:' +(depth *20)+ 'px;')
3. Another solution for your question is using <script> tags immediately after your divs and putting the js part inside them. In this way you don't have to use fake styling style="#{myBean.value}" or window.onload event because you can directly call #{myBean.value} in your script.
I decided to skip the javascript approach and settled on a simpler and I think cleaner method to create the dynamic css classes for my situation. I already capture/calculate the depth value for each comment when it is entered. So I am just returning that value in EL and concatenating it to a 'base name' for the css class like so:
<div class="indent_#{(comment.commentDepth le 5) ? comment.commentDepth : 5}" >
comment comment blah blah blah
</div>
"indent_" is the base name for the css class. So for a 0 level comment it will have a class="indent_0". A reply to that comment will have class="indent_1".
I use the ternary so that if there are lot of replies under a given comment it doesn't indent right off the right hand side of the page. Even though you can keep going deeper, it will only indent up to 5 levels.
For my case at the moment, this is a simpler and cleaner method of adding some dynamically generated css class names. Right now I have to define 6 classes for this in the css file, but perhaps I'll figure out how to nest the boxes but it isn't a priority this works just fine for me for now.

Grab a single digit out of a big mess of html

I am grabbing a div from the document with :
var myTotal = window.document.getElementById('status').innerHTML;
which returns a big mess of HTML
<div id="foo">
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
<img src="foo.gif" alt="foo" height="22px;/" width="15px;"></a>
</div>
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
MY TOTAL:
<span style="font-size: 12px; color: #F3A428; font-weight:normal;"> 8 item(s) </span>
</a>
Can one of you expression wizards please show me how I can grab just the number in the span, in this example an 8 ?
Can you give the span an id and reference it directly?
If not, then this regex should return the number in the span: /<span[^>]+>\s*(\d+)/
I'm assuming that there is only ever one span in the div.
This should help you
var myTotal = window.document.getElementById('status').getElementsByTagName('span')[0].innerHTML
myTotal = myTotal.replace(/(^\d+)(.+$)/i,'$1');
In jQuery, without even getting the inner HTML it would be this:
var items = $("#status span").first().text();
items = parseInt(items, 10);
alert(items); // 8
If you control the HTML, it would be advisable to put a unique ID on the span containing the result and then it's easier to retrieve and not dependent upon the structure around it or better yet, have it output into the page as a JS variable that you can just directly read and not have to deal with the presentation.
Seen in a jsFiddle here: http://jsfiddle.net/jfriend00/UqcxS/
You can also try, just using innerText
window.document.getElementById('status').innerText.replace(/[^0-9]/gi, '');
http://jsfiddle.net/X9ffE/
Use jQuery instead, it has a lot of functions that can help you find specific elements in your page. Also, you may want to add identification for your elements like class and id.

Count Upwards for ID jQuery

I have the following HTML structure
<div id="test-1-yay"></div>
... bunch of code ...
<div id="test-2-yay"></div>
... bunch of code ...
<div id="test-3-yay"></div>
I was wondering how I can use jQuery to basically identify each of these "id's" and then apply some jQuery to them ? I'm new to this so little unsure ? Something like
if $('#test-1-yay' || '#test-2-yay' || '#test-3-yay') {
do stuff to all ID's
}
But the prob is I want this to continue as it could go to #test-201-yay, #test-202-yay etc ?
Thx
Why don't you add a class to the divs?
You could try something like:
$("div[id^='test']")
or
$("div[id$='yay']")
or try to combine the two
Manual
You could use a substring selector to get most of the way there:
var divs = $('div[id^=test-]'); // All divs with IDs starting with "test-"
...which would work better if you changed the naming convention a bit so the number was at the end. But I think I'd lean toward using some other aspect of the structure (the parent node), or a class, or a data-xyz attribute...
Edit A pair of substring selectors can do it:
var divs = $('div[id^=test-]').filter("div[id$=yay]");
That gets all of the ones whose IDs start with "test-" and then filters out the ones that don't end with "yay". Close, anyway...
you could do it like that:
$("div[id^=test-]").each(function(){ //selects all dives having the string 'test-' in it
$that = $(this)
$that.text($that.attr("id").split("-")[1]) //splits the sting by "-" and gives you out the middle part (in your case the number)
})
test it here http://jsfiddle.net/aj5Qk/1/

Categories

Resources