How to Get Element From Path Not Class or Id - javascript

I am struggling to find an answer for this, I want a way to talk about an element, but because of the system I am adding to I do can not reference by its Id as it is dynamic. I can specify the class name of its containing div though... In essence what I am looking for is something along the lines of:
var disAb=document.getElementBySomething("div.ContainerDiv select")
When I mention the term 'path' I mean how I would reference it in CSS (see code reference).
Thank you guys!

You want document.querySelector or document.querySelectorAll, then just reference it by its hierarchy path:
Sample HTML
<div class="ContainerDiv">
<table>
<tr>
<td>
<div>
<select>
<option>Some options</option>
</select>
</div>
</td>
</tr>
</table>
</div>
JS
Get single element
var select=document.querySelector("div.ContainerDiv table tr td div select");
select.id = "someid";
For more than one element
var selects=document.querySelectorAll("div.ContainerDiv select");
selects[0].id = "someid";
Of course you do not need each part of the hiearchy, for instance you could just use: div.ContainerDiv select or div.ContainerDiv table select etc.

Related

How do you add a list id to a newly created HTML element?

How do I dynamically add text inputs to a table while assigning the same list id?
My code is currently:
function addspeakers(){
for(j=0; j<10;j++){
var cellid='inp'+cellnum;
input=document.getElementById('sprow').appendChild(document.createElement('input'));
input.placeholder='Country '+cellnum;
input.id='inp'+cellnum;
// add to list input.addtolist(countries);
cellnum++;
}
return
}
all it does is add 10 text inputs to a list however these lists have drop down menus...
This is the code for the datalist:
<datalist id='countries'>
and the text input elements should be created looking like this:
<table id='splist'>
<tr>
<td id='sprow'>
<input list='countries' placeholder='Country 1' id='inp1'>
</td>
</tr>
</table>
What do I need to add it to the list id?
Use setAttribute to set the property on the element.
input.setAttribute('list', 'countries');
Also since list is a not a default attribute of the element, but a custom attribute.
You can use data-* ( which is custom attributes)
<input data-list='countries'
input.setAttribute('data-list', 'countries');
You simply need to assign it like your other variables:
input.list='countries';
Also, you never use cellid, and your return is unnecessary ;)
Hope this helps!

How to find parent node of a row using jquery

From following html
<tbody>
<tr id="article0">
<td id="CheckboxDiv0">
<div class="checkbox">
<label>
<input type="checkbox" id="CheckboxArticle0" value="helo">
</label>
</div>
</td>
</tr>
</tbody>
I am trying to get the parent id
$ParentId = $("#checkboxArticle0").parentNode.parentNode.parentNode.parentNode.id;
The code is not working fine. Can someone suggest me how to grab the id of the parent div which is "article0"?
You can use .closest()
var parentId = $("#CheckboxArticle0").closest("tr").attr("id");
Description:
The closest() method returns the first ancestor of the selected element.
Refer: This for more.
Try like this
$("#checkboxArticle0").closest("tr").attr("id")
$("#checkboxArticle0").parents('tr').attr("id")
2 points to be note:
1) Use document.getElementById in javascript to access any element using its id,
2) You have mentioned wrong id , Use "CheckboxArticle0" instead of "checkboxArticle0" (C need to be capital letter)
Correct script is:
var ParentId=document.getElementById("CheckboxArticle0").parentNode.parentNode.parentNode.parentNode.id;
alert(ParentId)

Checking the names of elements from an array of objects selected by jquery

I'm a beginner in js and jquery library. I'd like to get an array of input fields with a particular name, and validate input. Each of my input fields have a name like NS[0], NS[1] etc. The total number of fields will have to be determined by the code, since the fields are generated by javascript.
I know that I can have jquery address the individual object like this:
$("input[name=NS\\[0\\]]").val() for <input type="text" name="NS[0]">.
However, how can I get an array of all these similiar elements, from NS[0] to NS[x] where x has to be determined based on how many fields have been generated? I already have other fields with different name patterns sharing the same css class, so using class is not an option. These boxes are in a particular div area, but in the same area are other input fields, so choosing all input boxes of the same area selects them as well.
In other words, how do I use jquery to check the name of each input field, after getting the entire array of input fields, to check each individual name?
Since I have input fields of various names in the area determined by the table id CNTR1, I would select them with $('#CNTR1 input'). I can also select individual fields by using $("input[name=]"). However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
The html code:
<table class="table" id="cnservers">
<thead>
<tr>
<th>Type</th>
<th>Preference</th>
<th>Value</th>
<th>Name</th>
</tr>
</thead>
<tr id="CNTR0">
<td>CNAME</td><td><input type="text" name="CN_PREF[0]" value=""></td><td>
<input type="text" name="CN_VAL[0]" value=""></td><td>
<input type="text" name="CN_NAME[0]" value="">
<a class="btn btn-danger" onclick="DelField(this.id);" id="CN_D0" >
<span class="btn-label">Delete
</span>
</a>
<a class="btn btn-primary" onclick="addField('cnservers','CN',10);" id="CN_A0" >
<span class="btn-label">Add
</span>
</td></tr>
</table>
[1]: http://i.stack.imgur.com/bm0Jq.jpg
I must be missing something. Is there a reason you can't use the http://api.jquery.com/attribute-starts-with-selector/?
$('#CNTR1').find('input[name^="NS"]')
Regarding,
However, what I want to do, is to select everything under $('#CNTR1 input'), and then run a loop on their names, checking whether the names match a predetermined criteria. How can I do that?
$("#CNTR1 input").each(function(index, elem) {
var $elem = $(elem),
name = $elem.attr('name');
var nameMatchesCondition = true; // replace with your condition
if (nameMatchesCondition) {
// do something!
}
});
EDIT 1:
Well, id is still an attribute of an html element. So you could do $('[id^="CNTR1"]') ... The value of the id attribute of an element doesn't contain the #. It's only part of the css/jquery selector. When using attribute style selectors, you don't need it. Though I can't comment on the performance of this.
Ideally, you want to attach a second class, say js-cntr to all elements that you created with an id starting with CNTR. Even though different name pattern elements may already have one class, that class is for styling. There is no stopping you from attaching custom classes purely for selection via js. This is an accepted thing to do and which is why the class name starts with js-, to denote that its purely for use via js for selection.
Try this
HTML
<table id="CNTR1">
<tr>
<td>CNAME</td>
<td><input type="text" name="CN_PREF[1]" id="CN_IN[1]"></td>
<td><input type="text" name="CN_VAL[1]"></td>
<td><input type="text" name="CN_NAME[1]"></td>
</tr>
</table>
JS
$(document).ready(function(){
$("#CNTR1 input").each(function() {
console.log($(this).attr("name"));
// Match With predetermined criteria
});
});
Use jQuery's .filter method, with a filter function:
filterCritera = /^CN_NAME\[/; // or whatever your criteria is
var inputs = $('#CNTR0 input');
// you could also cache this filter in a variable
inputs.filter(function(index){
return filterCritera.test(this.name);
}).css('background','red');
jsbin
The markup you posted does not the markup described in your question ( it does not contain NS[0]) but you can substitute it in the reguluar expression above.

Change with jQuery a cell of a table created with JSF

From within a xhtml page created with JSF, I need to use JavaScript / jQuery for changing the content of a cell of a table. I know how to assign a unique id to the div containing the table, and to the tbody. I can also assign unique class names to the div itself and to the target column. The target row is identified by the data-rk attribute.
<div id="tabForm:centerTabView:personsTable" class="ui-datatable ui-widget personsTable">
<table role="grid">
<tbody id="tabForm:centerTabView:personsTable_data" >
<tr data-rk="2" >
<td ... />
<td class="lastNameCol" role="gridcell">
<div> To Be Edited </div>
</td>
<td ... />
</tr>
<tr ... />
</tbody>
</table>
</div>
I have tried with many combinations of different jQuery selectors, but I am really lost. I need to search my target row and my target column inside that particular div or inside that particular table, because the xhtml page may contain other tables with different unique ids (and accidentally with the same row and column ids).
Something like this?
$("#tabForm\\:centerTabView\\:personsTable tr[data-rk=2] td.lastNameCol div").text("edited");
Or if personsTable is unique enough in the current view
$("[id$=personsTable] tr[data-rk=2] td.lastNameCol div").text("edited");
Please check this fiddle for your new html code
Fiddle without colon
Fiddle with Colon

How to remove an element without id

I have the following code:
<%-- other tags --%>
<table>
<tr width="100%">
<td width="130" />
<td id="BottomCell" width="100%" />
</tr>
<tr>
<td/>
<td/>
</tr>
</table>
<%-- other tags --%>
There may be more than one table on the page. I want the td before "BottomCell" to be removed (or hidden) when the page is loaded. How can I do this with javascript or css?
Thanks.
BTW, I'm developing a Sharepoint WebPart that will be put onto a page. The is on that page, which i don't have control of directly. But the WebPart should remove this as long as it shows up on the page.
Wow, going back to basics after using a framework is hard work.
var element = document.getElementById('BottomCell').previousSibling;
var parent = element.parentNode;
parent.removeChild(element);
In jQuery:
$('#BottomCell').prev().detach();
Well, assuming you have only one table, then you could do something like this (in javascript):
var firstCell = document.getElementsByTagName('tr')[0].getElementsByTagName('td')[0];
firstCell.parentNode.removeChild(firstCell);
It would get the first cell of the first row in the entire DOM tree, and remove that cell.
tr > td should do the trick.
Child and Sibling selectors
http://css-tricks.com/child-and-sibling-selectors/
#diodeus if there are only 2 data cells that would be acceptable, however if you wish to remove the first data cell regardless of however many cells are located in that row, you can do something like
var el = document.getElementById('BottomCell');
el.removeChild(el.parentNode.firstChild);
In jQuery I would find the parent and use the :first selector probably

Categories

Resources