Reputation: 11
I have an HTML file. I need to get the element attributes and but it's not happening as I am getting var elementType = target.getAttribute('data-type');
Uncaught TypeError: Cannot read property 'getAttribute' of null
I just don't know how I can get the element attribute. Please help.
var setAllEvents = $("[my-noteEvent]");
for (var i = 0; i < setAllEvents.length; i++) {
//call function to work with
this.bindingAllEvents(setAllEvents[i]);
}
bindingAllEvents: function(setElements) {
var element = document.getElementById(setElements.getAttribute('data-element')); // Get Element the event is set on
var target = document.getElementById(setElements.getAttribute('data-target')); // Get Element that is the target of the event
var event = setElements.getAttribute('data-event'); // What type of event to run
var action = setElements.getAttribute('data-action'); // Action to take on event
var elementType = target.getAttribute('data-type');
if (elementType === 'dropdown-label') {
target = target.parentelement;
}
element.addEventListener(event, function(e) {
e.preventDefault();
//do something here when all is good
});
}
<div class="form--input form--input-container form--select hasPlaceholder" data-type="dropdown-label" data-required="true">
<label for="countries">Dropdown</label>
<input type="hidden" id="countries" name="maritalStatus">
<input class="input--main" type="button" data-element="select" value="">
<span class="placeholder">A Dropdown with stuff</span>
<span class="selectChoice"></span>
<div class="framework dropdown dropdown--select-container">
<div id="" class="framework dropdown--select-item" data-value="UK" data-option="0">
<p class="framework text--paragraph ">
UK
</p>
<span class="dropdown--item-line"></span>
</div>
<div id="" class="framework dropdown--select-item" data-value="Russia" data-option="1">
<p class="atom text--paragraph ">
Russia
</p>
<span class="dropdown--item-line"></span>
</div>
</div>
</div>
<div my-noteEvent="" data-element="maritalStatus" data-target="myTarget" data-event="onchange" data-action="[{'Single':{'show':'#div1 #div3'}, {'married':{'show':'#div1 #div3'}}]">
</div>
Upvotes: 0
Views: 146
Reputation: 20154
I quote
<div my-noteEvent="" data-element="#maritalStatus" data-target="myTarget" data-event="onchange" data-action="[{'Single':{'show':'#div1 #div3'}, {'married':{'show':'#div1 #div3'}}]">
In your html, your attributes are named data-element="#maritalStatus" data-target="myTarget" respectively, yet you add an s at both in your code:
var element = document.getElementById(setElements.getAttribute('data-elements')); // Get Element the event is set on var target = document.getElementById(setElements.getAttribute('data-targets'));
remove the s at the end.
Furthermore if you are going to fetch by id using document.getElementById(variable), variable shouldn't start with a pound sign.
remove # in #maritalStatus
You are getting an error because target is null since you can't find it.
Upvotes: 1