user10481445
user10481445

Reputation:

how to get parent's child's value in javascript

when i click "download" word I want to get value of a tag which is bullet01.png

I searched parent()->child(), siblings() but it didn't work to me.

I need to use onclick function. bacause jquery don't work in my code, but when i use inside of onclick, it works.

so i use like this

onclick="downloadClick(fileList0)"

there is more tr tags and more td's id value

i made list from javascript

i set this fucntion for window.onload

function showOk() {
  $.ajax({
    url: 'http://localhost:8090/curriculum1.4/login_controller.jspx?cmd=fileList',
    type: 'get',
    dataType: 'json',
    success: function(resp) {

      var obj = JSON.parse(resp.file.result);

      var list4;
      var a4;
      var node;
      var element;

      for (i = 0; i < Object.keys(obj.univ).length; i++) {
      //  console.log(obj.univ[i].file);
        list4 = document.createElement("li");
        a4 = document.createElement("a");
        node = document.createTextNode(obj.univ[i].file);
        a4.setAttribute('href', obj.univ[i].file);
        list4.appendChild(a4);
        a4.appendChild(node);

                var num=i;
                var inte='fileList'+num;
                console.log(inte);

                element = document.getElementById(inte);
        element.appendChild(list4);

      }

    },
    error: function(xhr, status, error) {
      alert("오류입니다.");
    }
  });
}

js file

function downloadClick(val) {
    var id = val;
    //var id= $(this +".selected li a").attr("href");
    console.log(id);
}

log of js

enter image description here

this is a simple .html

    <table width="500" cellpadding="0" cellspacing="0" border="1" class="blueone">

        <tr>
          <td><input type="checkbox" id="a2" name="전체동의" /></td>
          <td id="fileList0" class="selected">
            <li>
              <a href="bullet01.png">bullet01.png</a>
            </li>
          </td>
          <td><a class="checkBtn" onclick="downloadClick(fileList0)">download</a></td>
        </tr>
  <tr>
      <td><input type="checkbox" id="a3" name="전체동의" /></td>
          <td id="fileList1">
                <li>
                  <a href="bullet011.png">bullet011.png</a>
                </li>
      </td>
      <td><a class="checkBtn" onclick="downloadClick()">다운로드</a></td>
    </tr>
    <tr>
      <td><input type="checkbox" id="a4" name="전체동의" /></td>
      <td id="fileList2"></td>
      <td><a class="checkBtn" onclick="downloadClick()">다운로드</a></td>
    </tr>
    <tr>
      <td><input type="checkbox" id="a5" name="전체동의" /></td>
      <td id="fileList3"></td>
      <td><a class="checkBtn" onclick="downloadClick()">다운로드</a></td>
    </tr>
      </table>

Upvotes: 3

Views: 3564

Answers (4)

cantuket
cantuket

Reputation: 1592

@DacreDenny's answer is definitely more reliable/flexible/less brittle if you don't have the parent element's id, so I'd consider actually removing ids entirely and replacing with a common class instead then implementing his solution.

but...

If you already have the id then traversing the DOM from the target element is kind of pointless because, well, there should only be 1 element with that id in the document. If the ids are there then you could just use...

function downloadClick(id) {
    var parent  = document.getElementById(id);
        links = parent.querySelectorAll("li:nth-of-type(1) a:nth-of-type(1)"),
        firstHref = links[0].href;

    return firstHref;
}
<table width="500" cellpadding="0" cellspacing="0" border="1" class="blueone">

    <tr>
      <td><input type="checkbox" id="a2" name="sino" /></td>
      <td id="fileList0" class="selected">
        <li>
          <a href="bullet01.png">bullet01.png</a>
        </li>
      </td>
      <td><a class="checkBtn" onclick="downloadClick('fileList0')">download</a></td>
    </tr>
  </table>

@DacreDenny's solution may be more performant since its only query limited DOM nodes to begin with, but I believe querying ids is already fairly optimized.

Either way, you should note, there is another error in your code as well as the other solutions I've seen...

downloadClick(fileList0)

needs to take he id name as a string not a JS variable...

downloadClick('fileList0')

Upvotes: 1

Skeets
Skeets

Reputation: 4848

"because jquery don't work in my code, but when i use inside of onclick, it works."

It sounds like you're including jquery, but it's not working.

That would be because your DOM elements are being loaded dynamically. You can't bind an event to an element before it exists.

You can, however, bind an element to the body of your HTML, and then filter for your element:

$("body").on("click", ".checkBtn", function(){
	var id = $(this).closest("tr").find(".selected li a").attr("href");
		
	console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width="500" cellpadding="0" cellspacing="0" border="1" class="blueone">
    <tr>
      <td><input type="checkbox" id="a2" name="전체동의" /></td>
      <td id="fileList0" class="selected">
        <li>
          <a href="bullet01.png">bullet01.png</a>
        </li>
      </td>
      <td><a class="checkBtn">download</a></td>
    </tr>
    <tr>
      <td><input type="checkbox" id="a2" name="전체동의" /></td>
      <td id="fileList0" class="selected">
        <li>
          <a href="bullet02.png">bullet02.png</a>
        </li>
      </td>
      <td><a class="checkBtn">download</a></td>
    </tr>
</table>

You don't need to use jQuery to do this (as the other answers have pointed out) but, if you already have jQuery loaded, then you might as well use it. :D

Note that in this approach, you don't need the "onclick" attribute in the HTML.

Upvotes: 1

random
random

Reputation: 7899

Get the element with id fileList0 having children a and then grab the textContent of it.

function downloadClick() {
    const value = document.querySelector('#fileList0 a').textContent;
    console.log(value);
}
<table width="500" cellpadding="0" cellspacing="0" border="1" class="blueone">
    <tr>
      <td><input type="checkbox" id="a2" name="전체동의" /></td>
      <td id="fileList0" class="selected">
        <li>
          <a href="bullet01.png">bullet01.png</a>
        </li>
      </td>
      <td><a class="checkBtn" onclick="downloadClick(fileList0)">download</a></td>
    </tr>
</table>

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30390

There are a number of ways to achieve this - one option is to add the reserved event object to your downloadClick() binding and method signature:

HTML:

<a class="checkBtn" onclick="downloadClick(event, fileList0)">download</a>

Javascript

function downloadClick(event, val) { 

Doing this gives you an easy means of determining the element that your user is currently clicking "from" (ie via the event objects currentTarget field). From there, you traverse the DOM via parentElement and querySelector (as outlined below) to locate and extract the href data you need:

/*  
  Add event parameter to function, allowing us to 
  determine the current element being clicked 
*/
function downloadClick(event, val) {

  /*
  Traverse up the tree via parentElement field. I've
  broken this into steps for clarity
  */
  var a = event.currentTarget;
  var td = a.parentElement;
  var tr = td.parentElement;

  /*
  User querySelector with selector matching DOM to access 
  the anchor element with data that you want to extract
  */
  var id = tr.querySelector('td li a').getAttribute('href');

  console.log(id);
}
<table width="500" cellpadding="0" cellspacing="0" border="1" class="blueone">
  <tr>
    <td><input type="checkbox" id="a2" name="전체동의" /></td>
    <td id="fileList0" class="selected">
      <li>
        <a href="bullet01.png">bullet01.png</a>
      </li>
    </td>
    <!-- Add event parameter to call -->
    <td><a class="checkBtn" onclick="downloadClick(event, fileList0)">download</a></td>
  </tr>
</table>

Upvotes: 2

Related Questions